-1

I have a Nodejs express server and an angularJs client which sends data to the server.

The problem is when I try to send a JSON to the server with angularJS, the received JSON becomes like this:

{"{\"question\":\"What will be result of code int a ":" 5/2\",\"answers\":[{\"a\":\"2.50\",\"b\":\"1\",\"c\":\"2\",\"d\":\"no right answer\"}],\"answer\":\"c\",\"score\":\"100\"}"}

Here is my post method in angularJS:

createQuestion: function(question){
  delete question["_id"];
      console.log(JSON.stringify(question))
        return $http.post('http://localhost:3000/questions/', question, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    })
        .then(
                function(response){
                    return response.data;
                },
                function(errResponse){
                    console.error('Error while creating question');
                    return $q.reject(errResponse);
                }
        );
    }

the output of console.log(JSON.stringify(question)) is:

{"question":"What will be result of code int a = 5/2","answers":[{"a":"2.50","b":"1","c":"2","d":"no right answer"}],"answer":"c","score":"100"}

Here is the part of the code in nodejs responsible for POST methods:

exports.create_a_question = function(req, res) {
  console.log(JSON.stringify(req.body))
  var new_question = new Question(req.body);
  new_question.save(function(err, question) {
    if (err)
      res.send(err);
    res.json(question);
  });
};

After a search I found out that this problem happens because of application/x-www-form-urlencoded in the header of requests but I add this configuration to my nodejs server and the problem still persists:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Here is CORS headers on nodejs server:

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Max-Ag', '3600');

How can I solve the problem?

8
  • If you want to send json, why use Content-Type: x-www-form-urlencoded? Also, angularjs doesn't strongify your data: stackoverflow.com/questions/24545072/… Commented Aug 24, 2018 at 13:19
  • Try removing headers from the $http.post request. Commented Aug 24, 2018 at 13:19
  • @Andrew because using application/json returns 404 on angular forum.ionicframework.com/t/… Commented Aug 24, 2018 at 13:29
  • @31piy I did that, but I get 404 error forum.ionicframework.com/t/… Commented Aug 24, 2018 at 13:30
  • @I've updated my question, including headers Commented Aug 24, 2018 at 13:49

3 Answers 3

0

The back slashes ("\") happen when JSON.stringify is called twice:

var x = {a:1, b:2};
var y1 = JSON.stringify(x);
var y2 = JSON.stringify(y1);
console.log(y2);

The AngularJS framework automatically does a JSON.stringify with the $http.post method. The second JSON.stringify was called in the Node.js code.

The solution is to use JSON.parse in the Node.js code:

var x = {a:1, b:2};
var y1 = JSON.stringify(x);
var y2 = JSON.parse(y1);
console.log(y2);

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

1 Comment

So I removed the unnecessary JSON.stringify from the angular when calling $http.post, and now I get the message in nodejs server as [Object object] and when I use JSON.parse(req.body) I get error Unexpected token o in JSON at position 1 and when I try to print an element of JSON with console.log(req.body["question"]) I get undefined in the console
0

So here is how I solved the problem: download the cors library via npm:

npm install --save cors

use it in the code:

var cors = require('cors');
app.use(cors());

then I removed the unnecessary header option when calling angularjs $http.post

Comments

-1

Possibly:

    headers: { 'Content-Type': 'multipart/form-data', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache'}

Since there are multiple content types at issue here ...

1 Comment

I still get 404

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.