【问题标题】:Issue while post from angularjs to WebAPI从 angularjs 发布到 WebAPI 时出现问题
【发布时间】:2017-01-10 09:31:35
【问题描述】:

我正在尝试将 Post 请求从 Angularjs 发送到 Web Api Action 方法。 WebApi 和 Angular 相关的代码运行在不同的端口中(因为它们在单个解决方案中的不同项目中)。在发出发布请求时我收到错误:

XMLHttpRequest cannot load "API method path here". Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:64648' is therefore not allowed access.

响应的 HTTP 状态代码为 405。我的 POst 调用如下:

var data = { 'obj': 'text' };

this.PostApiCall = function (controllerName, methodName, obj) {
    result = $http.post('localhost:49551/api/' + controllerName + '/' + methodName, obj)
    .success(function (data, status) {
        alert("All right");
        result = (data);
    }).error(function () { 
        alert("Something went wrong");
    });
    return result;
};

这似乎是与 CORS 相关的问题,我在我的 WebApiConfig 中包含了config.EnableCors();。在我的控制器中还包含[EnableCors(origins: "localhost", headers: "", methods: "")] 以允许来自本地主机的所有请求,因为我的发布请求来自本地主机。我仍然遇到同样的错误。知道丢失了什么吗?

注意:我在 localhost 所在的所有地方都有 Http://,我删除了 Http,因为我的问题中不允许包含超过 2 个链接。

【问题讨论】:

    标签: angularjs post asp.net-web-api cors


    【解决方案1】:

    您似乎正在为 $http 的实现基础而苦恼

    阅读此posting-form-data-with-http-in-angularjs

    我不确定,但请尝试使用 127.0.0.1 代替

    【讨论】:

    • 非常感谢,但是当我在同一个项目中使用我的 Angular 服务请求和我的 API 控制器尝试同样的事情时。一切正常。我可以通过 API 方法接收数据。
    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2016-04-17
    相关资源
    最近更新 更多