【发布时间】:2017-12-29 00:08:51
【问题描述】:
我有一个 aurelia 客户端和一个网络服务器。当我使用 localhost 并且我在同一台机器上运行时,它工作正常。
但是当我想从另一台机器访问服务器时,页面会加载,但 api 调用会出现以下错误:
请求的资源上没有 Access-Control-Allow-Origin 标头。
我正在使用 owin,但我不明白我需要为 owin 启用 CORS。
我在我的创业课上做了以下事情:-
更新 我已经用 Nenad 的输入更新了我的课程,但仍然遇到同样的错误。 下面我添加了来自客户端的调用。
public void Configuration(IAppBuilder app)
{
this.container = new Container();
// Create the container as usual.
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IWebDeps, WebDeps>(Lifestyle.Singleton);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration, Assembly.GetExecutingAssembly());
container.Verify();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// Configure Web API for self-host.
var config = new HttpConfiguration()
{
DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container)
};
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//// Custom Middleare
app.Use(typeof(CustomMiddleware));
app.UseWebApi(config);
//New code:
app.Run(context =>
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Hello, world.");
});
}
我的主程序正在调用 startUp 类:-
using (Microsoft.Owin.Hosting.WebApp.Start<Startup>("http://localhost:8080"))
{
Console.WriteLine("Press [enter] to quit...");
Console.ReadLine();
}
客户端代码,192.168.178.23 是来自服务器的 ip。
let baseUrl2 = "http://192.168.178.23:8080/api/status/getStatus";
getStatus() {
return this.client.get(baseUrl2)
.then(response => {
return this.parseJSONToObject(response.content);
});
}
Chrome 中的错误:
XMLHttpRequest 无法加载 http://192.168.178.23:8080/api/status/getStatus。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:9000” 使用权。响应的 HTTP 状态代码为 400。
现在应该启用 Cors 吧?但是在进行 api 调用时我仍然会收到错误消息。我错过了任何步骤吗?我们的这种方法错了吗?
欢迎提出任何建议!
【问题讨论】:
-
我会尝试添加行
app.UseWebApi(config);,也许需要将具有CORS设置的app与config中的路由相关联。