Sas*_*rey 54 api json httprequest node.js
这是我的模型与json响应:
exports.getUser = function(req, res, callback) {
User.find(req.body, function (err, data) {
if (err) {
res.json(err.errors);
} else {
res.json(data);
}
});
};
Run Code Online (Sandbox Code Playgroud)
在这里,我通过http.request获得它.为什么我收到(数据)字符串而不是json?
var options = {
hostname: '127.0.0.1'
,port: app.get('port')
,path: '/users'
,method: 'GET'
,headers: { 'Content-Type': 'application/json' }
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data); // I can't parse it because, it's a string. why?
});
});
reqA.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
reqA.end();
Run Code Online (Sandbox Code Playgroud)
我怎么能得到一个json?
Chr*_*sCM 73
http以字符串形式发送/接收数据......这就是事情的方式.您正在寻找将字符串解析为json.
var jsonObject = JSON.parse(data);
Run Code Online (Sandbox Code Playgroud)
dpi*_*eda 67
只是告诉请求您正在使用json:true并忘记标题和解析
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
和帖子相同
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
Jos*_*igo 12
只需设置json选项true,正文将包含解析的json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165732 次 |
| 最近记录: |