我使用Aurelia Fetch Client来查询我自己的Slim Framework RESTful API。API包含正确的报头(由Postman验证):
Access-Control-Allow-Headers →X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Cache-Control →no-store, no-cache, must-revalidate, post-check=0, pre- check=0
Connection →close
Content-Type →application/json;charset=utf-8
Expires →Thu, 19 Nov 1981 08:52:00 GMT
Host →localhost:8080
Pragma →no-cache
X-Powered-By →PHP/5.6.19
然而,我在Javascript控制台得到以下错误:
Fetch API cannot load http://localhost:8080/api/v1/calendar/2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
如果我使用谷歌浏览器的CORS扩展,我可以成功连接。(然而,第二个问题是CORS扩展似乎杀死了响应状态码,即使我的API返回403或500,也将所有内容更改为200。)
我的Aurelia代码是:
saveCalendar() {
this.httpClient.fetch('http://localhost:8080/api/v1/calendar/2', {
method: 'post',
body: json(data)
}).then(response => {
window.alert("Got a response: " + response.status);
if (response.status == 200) { // OK
window.alert("Calendar saved!");
} else { // Error
window.alert("Error");
}
});
this.getCalendars();
}
为什么Access-Control-Allow-Origin: *
不允许我从任何地方访问?
= = =编辑:
经过更仔细的观察,我看到Aurelia和Fetch正在发出2个请求。飞行前请求选项似乎很好,并在响应中接收CORS Access-Control-Allow-Origin: *
标头。然而,在实际的POST请求中,API没有返回任何东西。POST请求头如下:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,es-419;q=0.6,es;q=0.4,gl;q=0.2
Cache-Control:no-cache
Connection:keep-alive
Content-Length:142
content-type:application/json
Host:localhost:8080
Origin:http://localhost:9000
Pragma:no-cache
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36
当我将这些报头复制到Postman中以发出相同的请求时,它也以同样的方式失败。但是,如果我删除一个头(content-type:application/json
),它的工作。
我的Aurelia代码中的实际请求是这样的:
// src/common/api.js
import { inject } from 'aurelia-dependency-injection';
import 'fetch';
import { HttpClient, json } from 'aurelia-fetch-client';
@inject(HttpClient)
export class API {
constructor(httpClient) {
httpClient.configure(config => {
config
.withBaseUrl('http://localhost:8080/api/v1');
.withDefaults({
mode: 'cors',
headers: {
'Accept': 'application/json'
'Content-type' : 'application/json'
}
});
});
this.httpClient = httpClient;
}
getData(url) {
return this.httpClient.fetch(url)
.then(response => response.json());
}
postData(url, data) {
return this.httpClient.fetch(url, {
method: 'post',
body: json(data)
});
}
}
从Aurelia API客户端Fetch配置中删除'Content-type' : 'application/json'
似乎很明显,但即使我这样做,它仍然发送头。
最有可能的是,您运行在8080上的服务器需要配置为接受CORS请求,无论标题似乎不是这样说…
所述服务器的配置取决于运行该服务器的内容。一旦你澄清了这一点,我将更新那个答案。
我不知道你提到的扩展,它一定会做一些奇怪的事情,最终会给你带来更多的麻烦,但这只是我的意见。
您可能还想看一下这里:Aurelia Post with http-fetch-client产生一个选项请求