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

Time:04-20

I am using Postman to test my function and am using POST to send the request. Every time I send it, I get the error: 'Cannot POST /translate'. I added the code below for my route and function:

 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
  }

CodePudding user response:

You've misused the app.post method. First you create the url, as you have done, but then it requires a callback method inside the method parameters.

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

from the 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.
  • Related