当我在浏览器中输入somedomain.com/some_api_url?_var1=1
时,回复为{"1":"descriptive string"}
,其中1
是一个数字索引变量,其值可以从1
到{{1} }。在哪里"描述性字符串"是一些总结索引代表内容的文本。
如何将n
api网址中的JSON response
整合到下面非常简单的somedomain.com/some_api_url?_var1=1
和Node.js
示例中?
出于测试目的,下面显示的非常简单的Express.js
将返回" Hello World"当用户从其Web浏览器请求app.js
时。 需要对以下代码进行哪些具体更改,以便网络浏览器响应请求:
http : // localhost : 3000
而不是回复" Hello World"?
以下是Index is: 1
Description is: descriptive string
的当前代码:
app.js
这是我当前的尝试,导致控制台打印var express = require('express');
var http = require('http');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
,并且浏览器仍然挂起,因为没有任何内容作为Got a response: undefined
返回给浏览器:
response
var express = require('express');
var http = require('http');
var app = express();
app.get('/', function (req, res) {
var url = 'somedomain.com/some_api_url?_var1=1';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
示例代码改编自the example at this link。
答案 0 :(得分:1)
您实际上忘记返回回复res.send(data)
。像这样更改端点代码。还为内部响应对象使用不同的变量名称。我在这里使用response
。
app.get('/', function (req, res) {
var url = 'somedomain.com/some_api_url?_var1=1';
http.get(url, function(resonse){
var body = '';
resonse.on('data', function(chunk){
body += chunk;
});
resonse.on('end', function(){
var body = JSON.parse(body);
var text = '';
for (var key in body){
text += 'Index is: ' + key +
'\nDescription is: ' + body[key]
}
// The Description is: "descriptive string"
console.log("Got a response: ", fbResponse);
res.send(text);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
});
答案 1 :(得分:0)
使用express 4.14.0
尝试此代码正如@ Zohaib-Ijaz指出的那样,res被重新定义并且在没有重命名的情况下不会为res.send工作。此代码也会将其自身用于演示目的(因此您暂时可以忽略app.get('/some_api_url',
。
然后,一旦完成http.get,就可以使用该对象并根据需要进行打印。请记住,此代码不能防御JSON中的错误。
var express = require('express');
var http = require('http');
var app = express();
const PORT = 3000;
app.get('/', function (req, res) {
var url = `http://localhost:${PORT}/some_api_url?_var1=1`;
http.get(url, function (resInner) {
var body = '';
resInner.on('data', function (chunk) {
body += chunk;
});
resInner.on('end', function () {
var fullResponse = JSON.parse(body); // {"343",:"I've heard 344 is more"}
// code to pair the keys with their data in plain js
var indexKeys = Object.keys(fullResponse);
var replies = indexKeys.map((key) => {
return `Index is ${key}\nDescription is ${fullResponse[key]}`;
});
//note this injection of a <pre> tag is just so modern browsers
// will respect the newlines. it is not an HTML document or JSON
res.send(
`<pre>${replies.join("\n")}</pre>`
);
});
}).on('error', function (e) {
console.log("Got an error: ", e);
});
});
app.get('/some_api_url', (req, res) => {
var var1 = req.query.var1 || "343";
var value = `I've heard ${parseInt(var1) + 1} is more`;
var reply = {};
reply[var1] = value;
res.send(JSON.stringify(reply));
});
app.listen(PORT, function () {
console.log(`Example app listening on port ${PORT}!`);
});
答案 2 :(得分:0)
您似乎正在混淆Express,本机HTTP模块和HTTP客户端。
以下是用于发送您要查找的响应的服务器端代码。
var express = require('express');
var http = require('http');
var app = express();
// our "database"
var database = ['APPLE', 'BOOK', 'CAT', 'DOG', 'ELEPHANT'];
app.get('/', function (req, res) {
// apply query parsing only of the query parameter is specified
if ('itemId' in req.query) {
var itemId = req.query.itemId;
// index less than 0 will not yield anything from our "database"
if (itemId < 0) {
res.status(400).send('Invalid item id');
// the item index corresponds to one of the items in the "database"
} else if (itemId < database.length) {
var result = 'Index: ' + itemId + '<br>Description: ' + database[itemId];
res.send(result);
// index exceeds the size of the array, so nothing will be found
} else {
res.status(404).send('Item not found');
}
// render the default homepage
} else {
res.send('Request format: http://localhost:3000/?itemId=n');
}
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
要查看它的实际效果,请在浏览器中加载http://localhost:3000/?itemId=0
。有效itemId
值为0到4。