Javascript Nodejs服务器向客户端发送另一个对象

Javascript Nodejs服务器向客户端发送另一个对象,javascript,json,node.js,ajax,object,Javascript,Json,Node.js,Ajax,Object,我只是尝试将对象从客户端发送到nodejs服务器 Ajax调用: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, // application/x-www-form-urlencoded; charset=UTF-8 dataType: config.api.dataType, // JSON data: config.api.d

我只是尝试将对象从客户端发送到nodejs服务器

Ajax调用:

$.ajax({
  url: config.api.url,
  type: config.api.method,
  contentType: config.api.contentType, // application/x-www-form-urlencoded; charset=UTF-8
  dataType: config.api.dataType,       // JSON
  data: config.api.dataType === 'GET' ? {} : JSON.parse(tmp),
  headers: config.api.headers,
  success: (response) => { onSuccess(response); },
  error: (error) => { onError(error); }
});
已发送数据:

{
  sort: { name: 1 }
}
// I set name property by sort['name'] = 1; at js
但服务器收到:

{ 'sort[name]': 1 }
Nodejs server code:

exampleData = (req, res) => {
  var sort = req.body.sort;
  console.log(sort);       // undefined
  console.log(req.body);   // { ..., 'sort[name]': 1 }
}
Chrome表单数据:

所以,我不能像js代码中的对象那样正确地读取对象

我的nodejs服务器代码:

import * as bodyParser from 'body-parser';
import * as express from 'express';
import * as mongoose from 'mongoose';
import * as path from 'path';
import * as cookieParser from 'cookie-parser';

const app = express();
app.use(bodyParser.json({ limit: 1024*1024*20, type: 'application/json' }));
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(express.bodyParser({limit: '50mb'}));
app.use(cookieParser());

如何修复它?

尝试在js代码中将
contentType
更改为
application/json


contentType
在服务器和客户端的类型不同。

请考虑以下几点:

var x = { sort : {name:1} }

x["sort"] returns {name:1}

同样地

sort["name"] = 1 

sort = {name:1}

在您的服务器中,它没有将其视为JSON,因此问题在于您的服务器看到的是什么,它没有将其视为JSON,在服务器中,将内容类型设置为JSON(application/),它可能会工作。

您希望发生什么?您能写下一些您的nodejs代码吗?您好,就像我说的,AndrewLohr,我想接收像客户端对象一样的
{sort:{name:1}}
@NavyFlame我更新了我的代码,请参见更改:)更改内容类型标题是有害的,除非您更改内容以匹配!嗨@Quentin那么,更改客户端对象更好吗?
sort = {name:1}