【问题标题】:NodeJS run server for receiving POST and serve GETNodeJS 运行服务器以接收 POST 并提供 GET
【发布时间】:2014-11-05 15:45:03
【问题描述】:

1) 在本地机器上运行 NodeJS 服务器

2) 一台带有 App 的设备向 Node 服务器发出 POST 请求。

3) XAMPP 页面发出 GET 请求以获取发送到节点服务器的设备(从第 2 点开始)。

希望这很清楚。

这就是我所拥有的,但 GET 接收未定义。 POST 日志key1=value1

var http = require('http');
http.createServer(function (req, res) {

console.log(req.method);

var txt;

if(req.method == "POST") {

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');

    var url = require("url"),
        parsedUrl = url.parse(req.url, false), // true to get query as object
        queryAsObject = parsedUrl.query;

    txt = JSON.stringify(queryAsObject);

    console.log(txt);

} else {

    // for GET requests, serve up the contents in 'index.html'
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello Worldzz\n'); // I WANT TO PASS txt here. 

    console.log("jaa" + txt);
}


}).listen(1337, 'my.ip.here');
console.log('Server running at http://my.ip.here:1337/');

——更新。检查

function checkServer() {
    $.ajax({
        type: "GET",
        url: "http://my.ip.here:1337/",
        async: false,
    }).success(function( text ) {
        console.log("res" + text);
        $( "h2" ).text( text );
    });
}

【问题讨论】:

  • 服务器正常,代码中没有定义'txt',请问是什么问题?
  • 我有一个 index.html 和 script.js jquery Ajax GET
  • 那么,你期望得到什么,GET 请求会收到 'Hello Worldzz\n'
  • txt 已定义。就像我写的那样,我想得到 txt 我从 POST 中得到的东西。
  • @bboy 那是不可能的。 POST 部分仅在 POST 上输入。在 GET 请求上,txt 仍未定义。不过,您当然可以将txt 定义为更高的一个范围,以便为所有请求共享它。

标签: node.js post get httprequest


【解决方案1】:

这只是一个简单的范围问题。由于您希望所有请求共享同一个 txt var,因此您需要在所有请求都可以访问它的地方定义 txt

var http = require('http');
var txt;
http.createServer(function (req, res) {

    console.log(req.method);

    //var txt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2017-07-14
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多