2

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 }
}

Chrome Form Data: enter image description here

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?

4
  • what are you expecting to happen? Commented Apr 12, 2018 at 16:02
  • Could you write down some your nodejs code? Commented Apr 12, 2018 at 16:02
  • Hi @AndrewLohr Like i said, I want to receive { sort: { name: 1 } } like client object! Commented Apr 12, 2018 at 16:05
  • @NavyFlame I updated my code, please see change :) Commented Apr 12, 2018 at 16:08

2 Answers 2

3

Try to change contentType to application/json at your js code.

contentType are not the same type at server and client.

Sign up to request clarification or add additional context in comments.

2 Comments

Changing the content-type header is harmful unless you change the content to match!
Hi @Quentin so, is it better to change client object?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.