为什么 Postman 在 express 应用程序中为我的路线提供错误 'Cannot POST'?

Why is Postman giving me the error 'Cannot POST' for my routes in express app?

我正在使用 Postman 来测试我的功能,并正在使用 POST 来发送请求。每次发送时,我都会收到错误:'Cannot POST /translate'。我为我的路线和功能添加了以下代码:

 app.post('/translate'), async function(request, response) {
   const translatedText = await translateText(request)
   res.json(translatedText)
}

  async function translateText(request) {
    const text = request.body['text']
    const language = request.body['language']

    let [translations] = await translate.translate(text, language)
    translations = Array.isArray(translations) ? translations : [translations]
    return translations
  }

您误用了 app.post 方法。首先,您创建了 url,正如您所做的那样,但随后它需要一个回调方法 方法参数中。

// remove ) after '/translate'
app.post('/translate', async function(request, response) {
   const translatedText = await translateText(request)
   res.json(translatedText)
});

来自 express docs:

Route definition takes the following structure: app.METHOD(PATH, HANDLER) Where:

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.