发布到MEAN API时发生JSON Parse错误

时间:2018-05-17 18:24:40

标签: jquery json ajax mean-stack

我目前正在为一些高中CS学生项目建立一个后端,而我无法为我的生活找到他们的工作。每次发布帖子请求时都会收到此错误:

  

位于0的JSON中的意外标记e

我给他们发布到API的代码是:

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: {
        "email": "myEmail@students.berkeley.net",
        "password": "isilly"
    },
    dataType: 'json',
    success: function(data){
        runMySuccessFunction(data);
    },
    error: function(){
        alert("failed");
    },
    url: 'https://notmyrealurl.herokuapp.com/veggiegang/api/users'
});

任何原因导致它不起作用,我不是Node或Express的最佳选择而且我很难过

编辑:这是我正在使用的方法的后端代码:

app.post("/veggiegang/api/users", (req, res, next) => {
  console.log("check")
  console.log(req.body)
  const newUser = req.body;
  newUser.createDate = new Date();

  db.collection(VEGGIEGANGUSERS).insertOne(newUser, (err, doc) => {
    if (err) {
      handleError(res, err.message, "Failed to create new user.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
})

只是为了澄清,后端的post方法实际上并没有运行,因为JSON解析错误在它运行之前发生。我的两个console.log语句没有记录任何我说的原因。使用ARC进行测试时,该方法也可以正常工作,但我无法使JS代码工作。

1 个答案:

答案 0 :(得分:0)

您没有在请求中发送JSON,jQuery将传递给它的数据对象转换为url编码的key = value对。要获得JSON,您必须自己进行编码。

/(\w+)\s*=\s*"?[^"]+)/;