我正在尝试对我流式传输的一些推文使用情绪分析 API。有问题的 API 是这样的:http : //sentiment.vivekn.com/docs/api/。我以前在 Python 中做过这个,它按预期工作。我使用 requests 库发出了一个 post 请求,并发送了一个包含我的内容的 JSON 对象。JSON 对象如下所示:
{
"txt": "The content of the tweet."
}
在 Python 中,发送 post 请求看起来像这样:
url = "http://sentiment.vivekn.com/api/text/"
data_dict = {
"txt": "hi"
}
r = requests.post(url,json.loads(json.dumps(data_dict)))
print(r.text)
现在我承认我对 Javascript 和基于 Web 的编程总体上是新手,但我认为这两种语言的逻辑应该相似。我尝试使用 XMLHttpRequest 方法,但它总是返回带有状态代码的内部服务器错误:500。
该网站可以正常工作,它接受发布请求并通过分析做出响应,但我无法让它与 Node.js 一起使用。这就是我在 Javascript 中使用的内容:
const rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://sentiment.vivekn.com/api/text/',
body: {
"txt": "This is a very negative sentence, so we should get a negative analysis!"
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
console.log("Request received");
console.log(parsedBody);
})
.catch(function (err) {
console.log("Something went wrong\n" + err);
});
它总是捕获状态代码为 500 的错误。我尝试了其他几种方法,包括使用 XMLHttpRequest 发出请求。似乎没有任何效果。如果有人能指出我哪里出错了,那就太好了。
这不是答案,但我认为展示一些引起不同响应的代码很有用,这可能是有助于调试问题的线索。
我用 curl 得到相同的响应:
jim-macbookpro:~/development/node/so$ curl -X POST 'http://sentiment.vivekn.com/api/text/' -H "Content-Type: application/json" -d '{"txt": "hi"}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in theapplication.</p>
我将示例更改为使用“node-fetch”,但我没有得到 500,而是得到了 405 - 不允许使用的方法。
我怀疑这是服务器在某种程度上对请求的格式非常挑剔的问题。
我希望这有帮助。
const fetch = require('node-fetch');
fetch('http://sentiment.vivekn.com/api/text', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
txt:
'This is a very negative sentence, so we should get a negative analysis!'
})
})
.then(function(parsedBody) {
console.log('Request received');
console.log(parsedBody);
})
.catch(function(err) {
console.log('Something went wrong\n' + err);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句