我使用react与redux和axios异步操作。后端使用laravel 5.2 api。React在实际域中,api在子域中。当我尝试调用异步get请求到api时,我从网络得到200 Ok,但在控制台上得到错误。
Console Log:
XMLHttpRequest无法加载http://api.doublecurlybraces.me/api/test?api_token=inpm38XbI9Fof7CZv99VlfNQTjx02EjaL5V1B3###########. 预起飞请求响应未通过访问控制检查:否"访问-控制-允许-起源"标头出现在请求上资源。起源的http://doublecurlybraces。因此,"我"不是允许访问。
Network :
--General--
Request Method:OPTIONS
Status Code:200 OK
Remote Address:46.101.###.###:80
----
--Response Header--
Allow:GET,HEAD,POST
Cache-Control:no-cache
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Wed, 10 Aug 2016 15:08:01 GMT
Server:nginx/1.11.1
Transfer-Encoding:chunked
--Request Header--
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, access-control-allow-headers, access-control-allow-origin, x-requested-with
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:api.doublecurlybraces.me
Origin:http://doublecurlybraces.me
Referer:http://doublecurlybraces.me/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
# 操作代码
import axios from "axios";
var config = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers':'*',
'Access-Control-Allow-Origin' : 'http://doublecurlybraces.me',
'X-Requested-With': 'XMLHttpRequest'
},
params: {
api_token : 'inpm38XbI9Fof7CZv99VlfNQTjx02EjaL#############',
},
};
export function stockChanges(){
return function(dispatch){
axios.get('http://api.doublecurlybraces.me/api/test',config)
.then(function (response) {
dispatch({type : "FETCH_STOCK_FULFILLED" , payload : response.data})
})
.catch(function (error) {
dispatch({type : "FETCH_STOCK_REJECTED" , payload : error})
});
}
}
问题是服务器不返回Access-Control-Allow-Origin
标头。
Access-Control-Allow-Origin: http://doublecurlybraces.me
请注意,Access-Control-Allow-Origin
是一个响应头,所以您不应该将其添加到axios请求配置中。