node.js - 从 url 获取日期并返回 json

标签 node.js centos

使用简单的例子

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/

相关文章:

javascript - 控制台时间(秒)

node.js - 如何在express/mongoose中创建访问控制

linux - centOS 和 Virtualbox 中的内存增加

php - pecl_http 加载失败

javascript - 在 mongodb 中使用 $gt

node.js - 模拟无效的 HTTP 请求

javascript - 如何在 Pug 中获取对象的值?

ssh - 在 SSH 中重命名多个文件

linux - 在(CentOS 6.5)2.6.32内核中编译2.4.20内核

centos - 使用 CENTOS 上的所有 CPU 运行 c++ 程序