Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  188] [ 2]  / answers: 1 / hits: 48803  / 6 Years ago, sun, april 15, 2018, 12:00:00

In postman, I can successfully make this request:



enter



And get this response:



enter



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?


More From » node.js

 Answers
12

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 });

[#54660] Thursday, April 12, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;