[英]Testing for and parsing JSON response in Node.js/Express.js
运行Express.js的Node.js服务器通过将POST
发送到http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl
来处理对mydomain.com/myurl
的HTTP GET
。 响应以简单的JSON形式返回。
需要将以下代码添加到下面的routes.js文件中:
1.)在对mydomain.com/myurl的请求仅为JSON的情况下,创建一个单独的处理块
2.)按名称手动将JSON响应元素传输到variable1,variable2,variable3等?
这是routes.js
,它处理服务器端路由:
var url = require('url');
module.exports = function(app) {
app.get('/myurl', function(req, res) {
app.post('http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl', function(req, res) {});
console.log('The POST is finished. Waiting for response.');
//need separate handler for JSON response that comes back from the other domain after this
});
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the front-end)
});
};
POST http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl
的响应可能类似于:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"var_one":"value1",
"var_two":"value2",
"var_three":1100
}
您的app.post
调用不会向其他服务器发出POST请求,这是为了在您的服务器上设置POST路由。 如果您要向其他服务器发出HTTP请求,则最好使用诸如request之类的库。 然后,您可以使用JSON.parse
将响应JSON转换为本机JavaScript对象。
例:
var url = require('url');
var request = require('request');
module.exports = function(app) {
app.get('/myurl', function(req, res) {
request.post('http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl', function(err, response, body){
if(err){
//handle error here
}
var data = JSON.parse(body);
var variable1 = data.var_one;
var variable2 = data.var_two;
var variable3 = data.var_three;
//Do more processing here
});
console.log('The POST is finished. Waiting for response.');
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.