我使用(Dropzone js)上传ajax文件。它将文件发送到我的 hapi 服务器。我意识到浏览器发送了一个预检选项方法。但我的 hapi 服务器似乎没有发送正确的响应 header ,所以我在 chrome 上收到错误。 这是我在 chrome 上遇到的错误
XMLHttpRequest cannot load http://localhost:3000/uploadbookimg. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
这是 hapi js 路由处理程序
server.route({
path: '/uploadbookimg',
method: 'POST',
config: {
cors : true,
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: require('./books/webbookimgupload'),
}
});
根据我的理解,hapi js 应该发送来自 Pre-fight (OPTIONS) 请求的所有 cors header 。 无法理解为什么它不是
来自 Chrome 的网络请求/响应
**General**
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:3000
**Response Headers**
view parsed
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
cache-control: no-cache
vary: accept-encoding
Date: Wed, 27 Apr 2016 07:25:33 GMT
Connection: keep-alive
Transfer-Encoding: chunked
**Request Headers**
view parsed
OPTIONS /uploadbookimg HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36
Access-Control-Request-Headers: accept, cache-control, content-type
Accept: */*
Referer: http://localhost:4200/books/upload
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
提前致谢
最佳答案
hapi cors: true
是一个通配符规则,允许来自所有域的 CORS 请求,但少数情况除外,包括 hapi's default whitelist 之外存在其他请求 header 。 :
[“接受”、“授权”、“内容类型”、“if-none-match”、“来源”]
See the cors
option section in the API docs under route options :
headers
- a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to['Accept', 'Authorization', 'Content-Type', 'If-None-Match']
.
additionalHeaders
- a strings array of additional headers toheaders
. Use this to keep the default headers in place.
您的问题是 Dropzone 随文件上传一起发送了几个不在此列表中的 header :
x-requested-with
(不在上面的 header 中,但已为我发送)缓存控制
您有两种选择可以让事情正常工作,您需要在服务器或客户端上进行一些更改:
选项 1 - 将额外 header 列入白名单:
server.route({
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
method: 'POST',
path: '/upload',
handler: function (request, reply) {
...
}
});
选项 2 - 告诉 dropzone 不要发送这些额外的 header
通过他们的配置尚不可能,但有一个待处理的 PR 允许这样做:https://github.com/enyo/dropzone/pull/685
关于javascript - hapi.js Cors 飞行前不返回 Access-Control-Allow-Origin header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55477532/