Angular 2/Web Api - json 解析错误语法错误意外结束输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35734411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:18:17  来源:igfitidea点击:

Angular 2/Web Api - json parsing error syntax error unexpected end of input

jsonrestasp.net-web-apiangular

提问by aoakeson

I have a Web API controller that looks like this:

我有一个像这样的 Web API 控制器:

    [HttpPost]
    public IHttpActionResult Test()
    {
        return Ok();
    }

This is correct syntax, However when I try to call this from a service in Angular 2, I get the error message: "json parsing error syntax error unexpected end of input." To resolve this issue, I have to put a value into the ActionResult such as

这是正确的语法,但是当我尝试从 Angular 2 中的服务调用它时,我收到错误消息:“json 解析错误语法错误意外的输入结束。” 要解决此问题,我必须在 ActionResult 中放入一个值,例如

return Ok(1)

Am I missing some configuration? My Angular 2 service call looks like this:

我错过了一些配置吗?我的 Angular 2 服务调用如下所示:

return this.http.post(API/Controller/Test).map(res => res.json());

回答by JeromeXoo

Another way:

其它的办法:

All my http.get, post or put call (for uniformity):

我所有的 http.get、post 或 put 调用(为了统一):

.map(this.extractData)

In extractData (UPDATED: thanks to raykrow feedback, short code):

在 extractData 中(更新:感谢 raykrow 反馈,短代码):

private extractData(res: Response) {        
    return res.text() ? res.json() : {}; ;
}

回答by Thierry Templier

I guess that when you receive an empty response (without payload) you don't need to call the jsonmethod. Under the hood, the XHR response is undefined, JSON.parse(undefined)is called and an error is thrown.

我猜当您收到空响应(没有有效负载)时,您不需要调用该json方法。在幕后,XHR 响应未定义,JSON.parse(undefined)被调用并抛出错误。

You could skip the call of the mapoperator:

您可以跳过map操作员的调用:

return this.http.post(API/Controller/Test)/*.map(res => res.json())*/;

回答by Matt

Strictly speaking if your API is returning an OK code with no content you should return 204 (no content) - Angular would also be happy with this and not try to parse anything. So your controller method would become:

严格来说,如果您的 API 返回一个没有内容的 OK 代码,您应该返回 204(无内容) - Angular 也会对此感到满意,并且不会尝试解析任何内容。所以你的控制器方法将变成:

[HttpPost]
public IHttpActionResult Test()
{
    return NoContent();
}