【问题标题】:angularjs malforms json while sending data to the server using POSTangularjs 在使用 POST 向服务器发送数据时导致 json 格式错误
【发布时间】:2019-01-30 23:39:51
【问题描述】:

我有一个 Nodejs express 服务器和一个将数据发送到服务器的 angularJs 客户端。

问题是当我尝试使用 angularJS 向服务器发送 JSON 时,收到的 JSON 变成这样:

{"{\"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\"}"}

这是我在 angularJS 中的 post 方法:

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

console.log(JSON.stringify(question)) 的输出是:

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

这是nodejs中负责POST方法的部分代码:

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

经过搜索,我发现这个问题是由于请求标头中的application/x-www-form-urlencoded 而发生的,但是我将此配置添加到我的nodejs服务器并且问题仍然存在:

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

这是 nodejs 服务器上的 CORS 标头:

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');

我该如何解决这个问题?

【问题讨论】:

标签: angularjs json node.js express


【解决方案1】:

可能:

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

由于这里有多种内容类型存在争议...

【讨论】:

  • 我还是得到 404
【解决方案2】:

JSON.stringify 被调用两次时,会出现反斜杠("\"):

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

AngularJS 框架使用$http.post 方法自动执行JSON.stringify。第二个JSON.stringify 在Node.js 代码中被调用。

解决办法是在Node.js代码中使用JSON.parse

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

【讨论】:

  • 所以我在调用 $http.post 时从 Angular 中删除了不必要的 JSON.stringify,现在我在 nodejs 服务器中将消息作为 [Object object] 并且当我使用 JSON.parse(req.正文)我收到错误 Unexpected token o in JSON at position 1 并且当我尝试使用 console.log(req.body["question"]) 打印 JSON 元素时,我在控制台中未定义
【解决方案3】:

所以这是我解决问题的方法: 通过 npm 下载 cors 库:

npm install --save cors

在代码中使用它:

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

然后我在调用 angularjs $http.post 时删除了不必要的标头选项

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2016-04-05
    • 2018-11-18
    • 2016-12-13
    • 1970-01-01
    • 2013-09-05
    • 2016-08-05
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多