Dre*_*ife 7 javascript json node.js express
抱歉 n00b 问题我有点卡住了所以我希望你们能把我放在正确的方向上。
我正在制作一个通过 NODEJS 从 REST API 检索数据的应用程序。(这是成功且有效的)。
然后我在 express 中有一个侦听 URL(我自己的 API),我通过转到浏览器http://localhost/api或使用 POSTMAN 来调用它。到目前为止一切顺利,我在控制台(节点控制台)中看到,当我看到 JSON 响应时,我的请求得到了完美的处理,但是,我还希望在浏览器或 POSTMAN 中将 JSON 响应视为 JSON 响应,而不仅仅是控制台 我知道我的(简单)代码中遗漏了一些东西,但我才刚刚开始......请帮助我,这是我的代码。
var express = require("express");
var app = express();
const request = require('request');
const options = {
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
}
};
app.get("/api", function(req, res) {
request(options, function(err, res, body) {
var json = JSON.parse(body);
console.log(json);
});
res.send(request.json)
});
app.listen(3000, function() {
console.log("My API is running...");
});
module.exports = app;
Run Code Online (Sandbox Code Playgroud)
非常感激!
要将 json 响应从 express 服务器发送到前端,请使用res.json(request.json)而不是res.send(request.json).
app.get("/api", function(req, res) {
request(options, function(err, res, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
}); //closing the request function
res.send(request.json) //then returning the response.. The request.json is empty over here
});
Run Code Online (Sandbox Code Playgroud)
尝试这样做
app.get("/api", function(req, res) {
request(options, function(err, response, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
res.json(request.json) //then returning the response.. The request.json is empty over here
}); //closing the request function
});
Run Code Online (Sandbox Code Playgroud)
非常感谢 ProgXx,结果我使用了相同的资源和响应名称。这是最终的代码。非常感谢ProgXx
var express = require("express");
var app = express();
const request = require('request');
const options = {
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
app.get("/api", function(req, res) {
request(options, function(err, output, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
res.json(json) //then returning the response.. The request.json is empty over here
}); //closing the request function
});
app.listen(3000, function() {
console.log("My API is running...");
});
module.exports = app;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28828 次 |
| 最近记录: |