SyntaxError: Unexpected token < in JSON Aurelia

SyntaxError: Unexpected token < in JSON Aurelia

我正在使用 Aurelia 构建网络应用程序。我想显示一个从列表视图传递参数 (id) 的详细信息页面。这是我的(简化,"Detail"是基础数据class)控制器代码:

    [HttpGet("[action]")]
    public IActionResult GetDetail(int _id)
    {
        var b = new Detail()
        var customjson = JsonConvert.SerializeObject(b, Formatting.Indented);
        return Ok(customjson);
    }

详情通过detail.ts中的activate()方法获取 class:

    constructor(http: HttpClient) {
    this.http = http;
}

activate(params: any) {
    this.http.fetch("api/Begroting/GetBegroting/" + params.id)
        .then(result => result.json as Promise<Begroting>)
        .then(data => {
            this.begroting = data;
            console.log(data);
        });
}

但是,当通过列表页面加载详细信息页面时,出现此错误:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. Testing the API via Swagger yields valid json and a status code 200.

暗示 API(call) 有问题。

我们调用了 api/Begroting/GetBegroting/_id 而不是将 id 指定为 GET 参数。结果是对 api 的调用将我们重新路由回 index.html。因此 JSON Aurelia 错误中的意外标记 <。

要修复它,请将 API 调用更改为 api/Begroting/GetBegroting/?_id= + params.id

OP 已经解决了他的问题,但为了向未来的读者说明可能发生的事情:

SyntaxError: Unexpected token < in JSON 是一个错误,通常在您请求不存在的资源时发生。服务器 return 是一个标准的 404 HTML 错误响应。

当客户端尝试将 HTML 文档解析为 JSON 时,客户端将失败(它是 <html> 标记的第一个 < 失败) .

客户端需要状态码而不是错误页面

这里更深层次的问题是服务器真的应该 return 一个 404 状态码 响应,这样客户端就知道请求失败了,并且赢了' 尝试处理它,就好像它成功了一样。毕竟,404 错误 html 页面伴随着 200 状态代码。

所以除了修复客户端的请求url(或服务器端的路由),服务器and/or客户端应该被配置为正确的状态码是return 编辑为好。我相信 Accept: application/json 会解决这个问题,尽管我还没有测试过。

以及 OP 的替代解决方案:

RESTful 服务背后的理念是您的 URI 代表资源;查询字符串非常适合列表中的 sorting/filtering/paging 参数等。 ID 类型属于路径,而不属于查询字符串。

将您的路由属性更改为:[HttpGet("[action]/{_id}")] 并且您的初始客户端代码应该再次工作。