Reputation: 23
I'm just trying to send object from client to nodejs server
Ajax call:
$.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); }
});
Sent Data:
{
sort: { name: 1 }
}
// I set name property by sort['name'] = 1; at js
But the server received:
{ '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 }
}
So, I can't read object correctly like an object at js code.
My nodejs server code:
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());
How can I fix it?
Upvotes: 2
Views: 61
Reputation: 2358
Consider the following:
var x = { sort : {name:1} }
x["sort"] returns {name:1}
also
sort["name"] returns 1
similarly
sort["name"] = 1
is same as
sort = {name:1}
in your server it is not considering it as a JSON, so the problem is in what your server is seeing, it is not thinking it as a JSON, in the server make the content type to be as json (application/) and it will probably work.
Upvotes: 0
Reputation: 1227
Try to change contentType
to application/json
at your js code.
contentType
are not the same type at server and client.
Upvotes: 3