我正在使用axios从VueJS前端发出请求。 CORS请求做两个调用,第一个是OPTIONS
的第二与所请求的,以便POST
在我的情况。
它在Chrome上可以完美运行,但是如果我使用Safari或Firefox,则只有OPTIONS
请求。他们不执行POST
请求。
PHP(我使用多尔康PHP):
public function JSONBuilderCORS($data, $code) {
$response = new Response();
$message = $this->getResponseDescription($code);
if ($this->request->getServer('HTTP_ORIGIN')) {
$response->setHeader('Access-Control-Allow-Origin', '*');
$response->setHeader('Access-Control-Allow-Credentials', true);
$response->setHeader('Access-Control-Max-Age', 86400);
}
if ($this->request->isOptions()) {
if ($this->request->getServer('HTTP_ACCESS_CONTROL_REQUEST_METHOD')) {
$response->setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
}
if ($this->request->getServer('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) {
$response->setHeader('Access-Control-Allow-Headers', '*');
}
$response->setStatusCode($code, $message);
$response->setContent($data);
return $response;
}
$response->setHeader('Content-Type', 'application/json');
$response->setStatusCode($code, $message);
$response->setJsonContent($data);
return $response;
}
VueJS:
let config = {
headers: {
'Access-Control-Allow-Origin' : '*',
'Content-Type': 'application/x-www-form-urlencoded'
}
};
axios.post('http://example.com/charge', {
firstname: this.firstname,
lastname: this.lastname,
amount: this.finalAmount * 100,
source: result.token.id
},config)
.then((response) => {
this.loading = false;
this.paid = true;
this.snackbarSuccess = true;
})
.catch((error) => {
this.loading = false;
this.snackbarError = true;
});
Firefox响应标题:
Access-Control-Allow-Credentials
1
Access-Control-Allow-Headers
*
Access-Control-Allow-Methods
GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin
*
Access-Control-Max-Age
86400
Connection
keep-alive
Content-Length
2
Content-Type
text/html; charset=UTF-8
Date
Wed, 30 Jan 2019 16:40:13 GMT
Server
nginx
Status
200 OK
Request headers (515 B)
Accept
text/html,application/xhtml+xm…ml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Access-Control-Request-Headers
access-control-allow-origin
Access-Control-Request-Method
POST
Connection
keep-alive
Host
example.com
Origin
http://localhost:8080
Referer
http://localhost:8080/payment
User-Agent
Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/65.0
我不明白为什么它不能在其他浏览器上运行?您能帮我吗?