javascript POST 请求的节点获取问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49841983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node-fetch problems with POST requests
提问by Sahand
In postman, I can successfully make this request:
在邮递员中,我可以成功提出这个请求:
And get this response:
并得到这个回应:
Now I want to do the same request in my server.js file in node.js:
现在我想在 node.js 中的 server.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:
这不起作用。这是我访问 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 bodyparameter 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.
由于请求在邮递员中工作得很好,我认为问题在于节点获取,或者我使用它的方式,特别body是在fetch()调用中如何提供参数。似乎 API 调用不包含我想要的内容,因为在浏览器中它说"size":0.
What should I do to fix this?
我该怎么做才能解决这个问题?
采纳答案by Grynets
You need to await for json.
您需要等待 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:
您也可以使用JSON.stringify()for body提出请求。并且管理您的 js 对象会更容易。像这样:
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 });


