读取请求体Node.js服务器

Reading request body Node.js server

本文关键字:js 服务器 Node 请求 读取      更新时间:2023-09-26

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

我有一个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。正文为空白。

我在这里错过了什么?谢谢!

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

可以通过req.paramsreq.query获取参数

但是在你的ajax调用你必须queryString你的数据