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?
Content-Type: x-www-form-urlencoded? Also, angularjs doesn't strongify your data: stackoverflow.com/questions/24545072/…headersfrom the$http.postrequest.