簡體   English   中英

Hapi - 啟用CORS

[英]Hapi - enabling CORS

我正在使用Node JS和Hapi(v17)編寫BE應用程序。 當服務器正在運行並且我嘗試使用POST方法調用端點時,我不斷收到錯誤消息:

Failed to load http://localhost:8001/login: 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:3000' is therefore not allowed access.

我想在服務器站點上啟用CORS ,但對我來說沒有任何作用。

這是我如何在服務器站點上啟用CORS:

const hapi = require('hapi')

const server = hapi.server({
    port: 8001,
    host: 'localhost',
    routes: { 
        cors: true
    } 
})

我也試圖為特定路線啟用cors,但這也沒有效果:

server.route({
        method: 'POST',
        path: '/login',
        config: {
            cors: {
                origin: ['*'],
                additionalHeaders: ['cache-control', 'x-requested-with']
            }
        },
        handler: async (request, reply) => {
            return User.login(request, reply)
        }
    })

有誰知道我應該怎么做才能啟用CORS並擺脫問題?

此外,瀏覽器的網絡選項卡還有一個屏幕截圖:

在此輸入圖像描述

編輯:

我添加了處理OPTIONS方法的路由,現在我有另一個問題。

Failed to load http://localhost:8001/login: Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.

以下是網絡選項卡中的內容:

在此輸入圖像描述

cors: {
            origin: [
                '*'
            ],
            headers: ["Access-Control-Allow-Headers", "Access-Control-Allow-Origin","Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"],
            additionalHeaders: ["Access-Control-Allow-Headers: Origin, Content-Type, x-ms-request-id , Authorization"],
            credentials: true
        }

您還應該定義一個合格的域,而不僅僅是*通配符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM