读取请求体Node.js服务器

时间:2016-10-10 15:15:48

标签: javascript node.js

所以,我正在创建一个应用程序,允许我在客户端输入一些数据,无论是手机还是在同一网络中运行的其他桌面。

我有一个Node.js服务器,可以回复我的请求,但我实际上无法在服务器端“读取”它们。

这是我的服务器代码

var http = require("http");

var parseString = require('xml2js').parseString;

var express = require('express')
var app = express();
var port = process.env.PORT || 8081;


var request = require('request');


app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);


// routes will go here
app.use('/static', express.static('.'));

var bodyParser = require('body-parser');
app.use('/browse', bodyParser.json()); // support json encoded bodies
app.use('/browse', bodyParser.urlencoded({ extended: true })); // support encoded bodies


app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});


// POST http://localhost:8081/browse
app.get('/browse', function(req, res) {
  var browseRequest = req.body.browseRequest;
  console.dir("browseRequest: ");
  console.dir(browseRequest);

    res.send(JSON.stringify("response"));

});

(我这里有多余的东西吗?)

这是我用于我的html页面的部分

// Create the XHR object.
    function createCORSRequest(method, url) {

      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        // CORS not supported.
        xhr = null;
      }
      return xhr;
    }


    // Make the actual CORS request.
    function makeCorsRequest() {
      // This is a sample server that supports CORS.
        var url = "http://192.168.0.100:8081/browse"
      var xhr = createCORSRequest('GET', url);
      if (!xhr) {
        alert('CORS not supported');
        return;
      }

        //xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

          var req = { "browseRequest": {
                "name": "Aaron",
                "type": "Consumer",
                "age": 21

          }};
          xhr.send(JSON.stringify(req));

    }

我在客户端上获取服务器发送的字符串,但我无法访问服务器中的browserequest,因为 req.body 将变为空白。

我在这里缺少什么? 谢谢!

1 个答案:

答案 0 :(得分:-1)

GET参数(主要)是无体的。 (Read this

您可以使用req.paramsreq.query

获取参数

但是在你的ajax电话中你必须queryString你的数据。