hapi.js Cors Pre-flight not returning Access-Control-Allow-Origin header

五迷三道 提交于 2019-11-29 09:54:46

The hapi cors: true is a wildcard rule that allows CORS requests from all domains except for a few cases including when there are additional request headers outside of hapi's default whitelist:

["accept", "authorization", "content-type", "if-none-match", "origin"]

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 to headers. Use this to keep the default headers in place.

Your problem is that Dropzone sends a couple of headers along with the file upload that aren't in this list:

  • x-requested-with (not in your headers above but was sent for me)
  • cache-control

You have two options to get things working, you need to change something on either the server or the client:

Option 1 - Whitelist the extra headers:

server.route({
    config: {
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    },
    method: 'POST',
    path: '/upload',
    handler: function (request, reply) {

        ...
    }
});

Option 2 - Tell dropzone to not send those extra headers

Not possible yet through their config but there's a pending PR to allow it: https://github.com/enyo/dropzone/pull/685

I want to add my 2 cents on this one as the above did not fully resolve the issue in my case.

I started my Hapi-Server at localhost:3300. Then I made a request from localhost:80 to http://localhost:3300/ to test CORS. This lead to chrome still blocking the ressource because it said that

No 'Access-Control-Allow-Origin' header is present on the requested resource

(which was not true at all). Then I changed the XHR-Request to fetch the url to a url for which I actually created a route inside HapiJS which - in my case - was http://localhost:3300/api/test. This worked.

To overgo this issue I created a "catch-all" route in HapiJS (to overgo the built-in 404 catch).

const Boom = require('Boom'); //You can require Boom when you have hapi

Route({
  method: '*',
  path: '/{any*}',
  handler: function(request, reply) {
    reply(Boom.notFound());
  }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!