Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-fetch problems with POST requests

In postman, I can successfully make this request:

enter image description here

And get this response:

enter image description here

Now I want to do the same request in my server.js file in node.js:

const fetch = require('node-fetch')
const SEN_URL =  "http://www.sentiment140.com/api/bulkClassifyJson" // URL of sentiment analysis
app.get('/api/sentimenttest', async (req, res) => {
  try{
    var sentiments = await fetch(SEN_URL, {method: "POST", body: {"data": [{"text": "I love you"}, {"text": "I hate you"}]}})
    console.log(sentiments)
    res.send(sentiments)
  }catch(error){
    console.log(error)
  }
})

This doesn't work. Here's what shows up in the browser when I go to localhost:5000/api/sentimenttest:

{"size":0,"timeout":0}

and here's the console output:

 Response {
   size: 0,
   timeout: 0,
   [Symbol(Body internals)]: 
    { body: 
       PassThrough {
         _readableState: [ReadableState],
         readable: true,
         _events: [Object],
         _eventsCount: 2,
         _maxListeners: undefined,
         _writableState: [WritableState],
         writable: false,
         allowHalfOpen: true,
         _transformState: [Object] },
      disturbed: false,
      error: null },
   [Symbol(Response internals)]: 
    { url: 'http://www.sentiment140.com/api/bulkClassifyJson',
      status: 200,
      statusText: 'OK',
      headers: Headers { [Symbol(map)]: [Object] } } }

Since the request works just fine in postman, I think that the problem is with node-fetch, or the way that I use it, specifically how the body parameter is provided in the fetch() call. It seems like the API call does not contain what I want it to, since in the browser it says "size":0.

What should I do to fix this?

like image 424
Sahand Avatar asked Apr 15 '18 12:04

Sahand


People also ask

Can you use fetch for POST request?

A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.

How do I make a node-fetch POST request?

The first thing we do is require() the Node-Fetch NPM package and assign it a variable name of fetch to use in our application. Then we create an object called body that holds the data we will include in our POST request. This includes the title , body , and userId items.

Does fetch work in node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node. js version to 17.5.

Does node-fetch throw error?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise. reject(error); .


1 Answers

You need to await for json.

var sentiments = await fetch(SEN_URL, {method: "POST", body: {"data": [{"text": "I love you"}, {"text": "I hate you"}]}})
//Here 
await sentiments.json()

Also you can make request with JSON.stringify() for body. And it will be easier to manage your js object. Like this:

var data = {data: [{text: "I love you"}, {text: "I hate you"}]};
var body = JSON.stringify(data);
var sentiments = await fetch(SEN_URL, { method: "POST", body: body });
like image 103
Grynets Avatar answered Oct 06 '22 20:10

Grynets