即使使用“Access-Control-Allow-Origin”,服务器也会响应405错误:'*'?
所以我graphql API是在https://gpbaculio-tributeapp.herokuapp.com/graphql我cnofigured上传,标题是这样的:即使使用“Access-Control-Allow-Origin”,服务器也会响应405错误:'*'?
const fetchQuery = (operation, variables) => {
return fetch('/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json()
})
}
我从MDN
For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.
,所以我试图发布在codepen的应用程式阅读,而这是我的错误:
Failed to load https://gpbaculio-tributeapp.herokuapp.com/graphql : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' https://s.codepen.io '
为什么它告诉我,它不通过“访问控制允许来源”的消息头,有什么错我的标题配置?
尝试设置CORS选项和访问控制允许来源头在服务器端。
const graphQLServer = express();
const corsOptions = {
origin(origin, callback) {
callback(null, true);
},
credentials: true
};
graphQLServer.use(cors(corsOptions));
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
graphQLServer.use(allowCrossDomain);
这可能会帮助你
您正在设置请求中的标头(在客户端)。需要在服务器端设置Access-Control-Allow-Origin
标头,并且在发出请求时,响应应该包含该标头。
此标题背后的原因是,并非每个网页都可以查询每个第三方域。能够从请求中设置这个头部会击败整个点。
CORS规范规定,对于资源的请求被“预检”与HTTP OPTIONS请求和应答头为选项必须包含头:
$ curl -I -X OPTIONS https://gpbaculio-tributeapp.herokuapp.com/graphql
HTTP/1.1 405 Method Not Allowed
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Allow: GET, POST
Content-Type: application/json; charset=utf-8
Content-Length: 97
Date: Sat, 23 Sep 2017 11:24:39 GMT
Via: 1.1 vegur
:
Access-Control-Allow-Origin: *
你可能会卷曲检查
添加OPTION处理有需要的头,所以你的服务器的答案:
$ curl -I -X OPTIONS https://example.localhost/
HTTP/1.1 204 No Content
Server: nginx/1.4.7
Date: Sat, 23 Sep 2017 11:27:51 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
Content-Type: text/plain; charset=utf-8
Content-Length: 0
问题是浏览器的跨源问题。
Access-Control-Allow-Origin
头应该由服务器的响应返回,头意味着可以访问该API的原始域。
客户端的请求通常采用标头Origin
,它的值是当前主机地址,如www.example.com
。
Access-Control-Allow-Origin
的值必须包含Origin
的值表示源可以访问此API服务。然后浏览器将继续请求。否则,浏览器将取消该请求。
的介绍:,Refre酒店到CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
但即使我已经试过访问控制允许来源:s.codepen.io仍然会返回错误? –
交叉原点的CORS解决方案需要服务器和客户端合作配置解决方案。而'Access-Control-Allow-Origin'头只是所有操作之一。更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – JiangangXiong