【问题标题】:getting date from url and return json从 url 获取日期并返回 json
【发布时间】:2012-02-09 00:16:42
【问题描述】:

使用简单的例子

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"}

【问题讨论】:

    标签: node.js centos


    【解决方案1】:

    为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);
    });
    

    希望对您有所帮助。

    【讨论】:

    • 找到了更好的方法 require('url').parse(req.url)
    【解决方案2】:

    您可以修改 .htaccess 文件以将 URL 解析为参数。看这个问题的例子:htaccess url as parameter

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多