【问题标题】:Angular: SyntaxError: Unexpected token < in JSON at position 0Angular:SyntaxError:位置 0 的 JSON 中的意外标记 <
【发布时间】:2018-09-30 18:55:38
【问题描述】:

尝试在 Visual Studio 2017 中使用 ASP.NET Core 和 Angular 执行 CRUD 操作。我收到以下异常:

SyntaxError: Unexpected token

这是我的服务代码

    getEmployees() {
    return this._http.get(this.myAppUrl + 'api/Employee/Index')
        .map((response: Response) => response.json())
        .catch(this.errorHandler);

这是我的 Web API 控制器代码:

[HttpGet]
[Route("api/Employee/Index")]
public IEnumerable<Employee> Index()
{
     return objemployee.GetAllEmployees();
}

这是我的组件代码:

import { Component, Inject } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { EmployeeService } from '../../services/empservice.service'
@Component({
    selector: 'fetchemployee',
    templateUrl: './fetchemployee.component.html',
    providers: [EmployeeService]
})
export class FetchEmployeeComponent {
    public empList: EmployeeData[];

    constructor(public http: Http, private _router: Router, private 
_employeeService: EmployeeService) {
        this.getEmployees();
    }

    getEmployees() {
        this._employeeService.getEmployees().subscribe(
            data => this.empList = data
        )
    }
}

interface EmployeeData {
     id: number;
     name: string;
     gender: string;
     department: string;
     city: string;
}

【问题讨论】:

  • 这意味着您从 API 返回的数据不是 JSON,而是 HTML。如果您查看开发人员工具网络选项卡,您能看到您的请求吗?你得到什么回应?
  • 用浏览器的开发者工具检查请求是否返回成功。状态码很可能是 500,这意味着服务器应用程序遇到了错误。在这种情况下,请检查您的服务器日志,看看出了什么问题。
  • 你找到原因了吗?

标签: angular asp.net-core visual-studio-2017


【解决方案1】:

用 Json() 方法包装你的 return 语句。将返回类型设置为 JsonResult。

[HttpGet]
[Route("api/Employee/Index")]
public JsonResult Index()
{
    return Json(objemployee.GetAllEmployees());
}

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 2020-10-31
    • 2021-10-22
    • 2021-05-21
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多