无法通过rest API从客户端ajax POST请求接收数据

Unable to receive data from clients ajax POST request through rest API

本文关键字:POST ajax 请求 数据 客户端 rest API      更新时间:2023-09-26

我在服务器上构建了一些rest API,从其他域调用它们,Get请求工作正常,但我在调用POST请求时面临一个问题。

我无法在服务器上接收客户端发送的数据。

服务器代码:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//var fn = require('fn')
var app = express();
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    // intercept OPTIONS method
    if ('OPTIONS' === req.method) {
        res.send(200);
    }
    else {
        next();
    }
};
// all environments
app.set('port', process.env.PORT || 3000);
app.use(allowCrossDomain);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
app.post('/user', user.saveUser);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

exports.saveUser = function(req, res) {
    var key = req.body.key; //fb,twitter,web
    var userData = req.body.userData;
    var result  = checkUser(userData,key);        
}

发出请求的客户端代码:

var data = { key: 'web', userData: userData }
$.ajax({
    method: "POST",
    //contentType: 'application/json',
    url: "www.acbd.com/user",
    //url:"http://prayable-21641.onmodulus.net/user",
    data: data,
    crossDomain: true,
    dataType: "json"
}).success(function (data, textstatus) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(data)
    console.log(textstatus)
}).error(function (data, textstatus) {
    console.log(data)
    console.log(textstatus)
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

我无法在服务器上获得key或userData,它说它们没有定义:

TypeError: Cannot read property 'key' of undefined

您忘记要求和使用body-parser中间件模块了。

还有,为什么内容类型被注释掉了?你需要它

服务端代码应该是这样的:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//var fn = require('fn')
//requiring body-parser
var bodyParser = require('body-parser');
var app = express();
var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  // intercept OPTIONS method
  if ('OPTIONS' === req.method) {
      res.send(200);
  }
  else {
      next();
  }
};
// all environments
app.set('port', process.env.PORT || 3000);
app.use(allowCrossDomain);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
// using body-parser
app.use(bodyParser());
app.post('/user', user.saveUser);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

还有,别忘了NPM安装:

npm install body-parser

//需要正文解析器,确保使用

安装它
npm install body-parser

var bodyParser = require('body-parser');

,然后使用

app.use (bodyParser.json ());

app.use (bodyParser.urlencoded ());

希望有帮助