[英]HTTP Request JSON: Unexpected .parse error - How do I exterminate it?
I am using IBM Bluemix to make a web service for a school project. 我正在使用IBM Bluemix为学校项目提供Web服务。
My project needs to request a JSON from an API, so I can use the data it provides. 我的项目需要从API请求JSON,因此我可以使用它提供的数据。
I am having trouble with the http request to the API service. 我对API服务的http请求遇到问题。 I get the following alert in the Windows 10 Command Prompt.
我在Windows 10命令提示符中收到以下警报。
"Syntaxerror: Unexpected Token"
“语法错误:意外的令牌”
I know there is something wrong with my JSON request, but is it exactly? 我知道JSON请求有问题,但这是真的吗?
Here is my .js
file and a print of the error screen I get when running it. 这是我的
.js
文件和运行它时得到的错误屏幕的打印图像。
/*eslint-env node*/ //------------------------------------------------------------------------------ // node.js starter application for Bluemix //------------------------------------------------------------------------------ // HTTP request - duas alternativas var http = require('http'); var request = require('request'); // cfenv provides access to your Cloud Foundry environment // for more info, see: https://www.npmjs.com/package/cfenv var cfenv = require('cfenv'); //chama o express, que abre o servidor var express = require('express'); // create a new express server var app = express(); // serve the files out of ./public as our main files app.use(express.static(__dirname + '/public')); // get the app environment from Cloud Foundry var appEnv = cfenv.getAppEnv(); // start server on the specified port and binding host app.listen(appEnv.port, '0.0.0.0', function() { // print a message when the server starts listening console.log("server starting on " + appEnv.url); }); app.get('/home1', function(res){ http.get('http://developers.agenciaideias.com.br/cotacoes/json', function(res){ var body = ''; res.on('data', function(chunk){ body += chunk; }); res.on('end', function(){ var json = JSON.parse(body); }); var json = JSON.parse(res); var cotacao = json["bovespa"]["cotacao"]; console.log("A sua cotação é "+cotacao); }); });
You need to use the json object you created in .on('end'
您需要使用在
.on('end'
trying to JSON.parse res
when res
is clearly not a string is causing your error (res.toString() results in [Object object] ... hence the error as that is not valid JSON 当
res
显然不是字符串时尝试JSON.parse res
导致您的错误(res.toString()导致[Object object] ...因此错误,因为该错误无效JSON
app.get('/home1', function(res){
http.get('http://developers.agenciaideias.com.br/cotacoes/json', function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var json = JSON.parse(body);
var cotacao = json["bovespa"]["cotacao"];
console.log("A sua cotação é "+cotacao);
});
});
});
Try configuring app for parsing json body: 尝试配置用于解析json主体的应用程序:
app.configure(function () {
app.use(express.json())
})
You will recieve a parsed json object 您将收到一个已解析的json对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.