首页 > 解决方案 > SyntaxError:“JSON.parse:JSON 数据第 1 行第 1 列的意外字符”

问题描述

从我的 Angular 前端向我的 Node 后端发送 HTTP DELETE 请求时,会引发以下错误:

语法错误

但是,仍会处理 DELETE 请求并删除对象。

这是我在 Angular 中的删除功能:

  deleteProject(id: number) {
     this.http.delete(`projects/${id}`).subscribe(
      response => {
        this.toastr.success('Project deleted.', 'Success');
      },
      err => {
        console.log(err);
      }
    );
  }

在我的后端 API 中:

function remove(req, res) {

  let query = {
    _id : req.params.id
  };

  Projeto.findById(query)
  .then(async (projeto) =>  {

    if(!projeto) {
      return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
    }

    if(projeto.project_manager.toString() != req.user._id.toString()) {
      return res.status(403).json({error: 'forbidden', message: 'You can\'t delete this project.'});
    } else {
      await Projeto.findByIdAndRemove(query);
    }


    res.status(200).send("Project deleted.");


  })
  .catch(utils.handleError(req, res));
}

该错误指的是什么,我该如何解决?

标签: angularangular-httpclient

解决方案


我的 AspNet Core Web Api 后端出现了同样的错误。

当我们在 Ok 方法中返回一个值时:

Ok('some message') 它给出了这个错误:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

如果我们只使用Ok()没有任何消息,它工作得很好:)

这是我的工作控制器操作方法:

    [HttpPost("{receiverId}")]
    public ActionResult LikeUser(int userId, int receiverId)
    {
         var result = _likeRepository.LikeUser(userId, receiverId);

         if(result.IsSuccessful)
            return Ok();
        else
            return BadRequest(result.Message);
    }

推荐阅读