使用简单的例子
var server = http.createServer(function(req, res){
var output = {message: "Hello World!"};
var body = JSON.stringify(output);
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
});
res.end(body);
});
我可以返回 json 对象。我怎样才能从这样的请求中返回一些参数
url: http://localhost:8080/get/jhon
output: {"message": "Hello jhon"}
最佳答案
为 request.url
添加一个检查器
基本上,以您自己的代码为例:
var server = http.createServer(function(req, res){
var output = {message: "Hello World!"};
var body = JSON.stringify(output);
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
});
//.split creates an array with strings from the given url
//req.url -> gives everything that's right after the http://localhost:8080/ portion
var requested = req.url.split("/");
output.message = "Hello " + requested[2]; // 0 is empty, 1 is "get"
res.end(output);
});
希望对您有所帮助。
关于node.js - 从 url 获取日期并返回 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8839646/