简体   繁体   English

AJAX post to Express 不返回任何数据到 req.query (是的,有相同的 q 但没有任何效果)

[英]AJAX post to Express returns no data to req.query (yes there is the same q but nothing works)

this is my set up.这是我的设置。 However when I send data through the ajax the body is empty.但是,当我通过 ajax 发送数据时,正文是空的。 On chrome under network I see the post and the content, with a correct payload:在网络下的 chrome 上,我看到帖子和内容,以及正确的有效负载:

请求

{"EventName":"asd","PrivacyLevel":1,"TypeInt":1,"ExpectedDate":"asd","Desc":"asd","Down":0,"Up":0,"PostCode":"","Address":"","ID":""}

Most people say its the body parser, I have placed the parsers above the app.use(app.router) I dont know if it creates any conflict with express.json() but when I commented it out it didnt make any difference.大多数人说它是正文解析器,我将解析器放在 app.use(app.router) 上方,我不知道它是否与 express.json() 产生任何冲突,但是当我将其注释掉时,它没有任何区别。

   app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());
    app.use(express.cookieParser('secret'));
    app.use(express.session({ secret: 'randomstring' }));
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));

$.ajax({
    url: window.location.origin + '/registerEvent',
    contentType: 'application/json: charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(Event.toJSONString()),
    cache: false,
    timeout: 5000,
    async: false,
    success: function (result) {
        success = true;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('error ' + textStatus + " " + errorThrown);
        success = false;
    }
});

exports.registerEvent = function (req, res) {
    if (req.session.lastPage === '/index' && req.xhr) {
        console.log(req);
        console.log(req.body);
        console.log('body: ' + JSON.stringify(req.body));

        var test = req.query.EventName;

The data will be available in req.body (the parsed HTTP request body from the AJAX JSON) not req.query (the URL query string).数据将在req.body (来自 AJAX JSON 的解析 HTTP 请求正文)而不是req.query (URL 查询字符串)中req.query

In your jquery ajax code, use contentType: 'application/json' and that should get it doing the kind of POST request you want.在您的 jquery ajax 代码中,使用contentType: 'application/json'这应该让它执行您想要的那种 POST 请求。

I think you found a bug in Connect (the middleware that Express uses to parse the body).我认为您在 Connect(Express 用来解析正文的中间件)中发现了一个错误。 The code for the bodyParser uses a regular expression to match the "application/json" content type that fails when the "charset=utf-8" is appended to it. bodyParser 的代码使用正则表达式来匹配在附加“charset=utf-8”时失败的“application/json”内容类型。

Here is the Connect.js code that I am talking about: https://github.com/senchalabs/connect/blob/master/lib/middleware/json.js#L54这是我正在谈论的 Connect.js 代码: https : //github.com/senchalabs/connect/blob/master/lib/middleware/json.js#L54

The RegEx that Connect is using is Connect 使用的正则表达式是

/^application\/([\w!#\$%&\*`\-\.\^~]*\+)?json$/i

If you run the following code Node you'll see that the one with "charset=utf-8" fails the test:如果您运行以下代码 Node,您将看到带有“charset=utf-8”的代码未通过测试:

regex = /^application\/([\w!#\$%&\*`\-\.\^~]*\+)?json$/i
regex.test("application/json") // returns true
regex.test("application/json: charset=utf-8") // returns false

在我的情况下,我解决了这个问题:

res.header("Access-Control-Allow-Origin", "*");

I copied the code generated by Postman and it worked for me.我复制了 Postman 生成的代码,它对我有用。

Instead of using my normal code而不是使用我的普通代码

$.ajax({
  url: 'http://localhost:3001/api/v1/signup',
  data: {
    first_name: 'jacob',
    last_name: 'ross',
    username: 'username',
    emailAddress: 'email@email.com',
    password: 'somepassword'
  },
  type: 'POST',
  contentType: 'application/json: charset=utf-8', // caused CORS issue
  success: function(d){
    console.log(d);
  }
})

I used this from Postman which worked just fine, and was able to access the params with req.query .我从 Postman 那里使用了这个,它工作得很好,并且能够使用req.query访问参数。

var settings = {
  "url": "http://localhost:3001/api/v1/signup?email=email@email.com&password=123456789&first_name=jacob&last_name=ross&username=jacobrossdev",
  "method": "POST",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM