【问题标题】:Express Node.js Cors preflight issue 400 net::ERR_FAILEDExpress Node.js Cors 预检问题 400 net::ERR_FAILED
【发布时间】:2020-10-21 06:46:53
【问题描述】:

我已经把头撞在墙上好几个小时了……尝试了各种组合来让它发挥作用。

我在这里有自己的 API 端点:https://app.automate.mn/api/tools/email/add

我正在尝试从 3rd 方网站向其发布数据。

app.js

const express = require('express');
const cors = require('cors');
const app = express();
    
app.use(cors());
app.options('*', cors());

...
    
const {addContact} = require('./routes/api/tools/email');
app.post('/api/tools/email/add', addContact);

addContact.js

addContact: async function (req, res) {

    res.status(200).send('OK - TEST');
    return;
}

我在这里设置了一个测试网站,格式为:https://demoautomatemn.wpcomstaging.com/

当您提交表单时,它会将数据发布到端点:

loadForm.js

automate_post_data('https://app.automate.mn/api/tools/email/add', data)
            .then(data => {
                console.log(data); // JSON data parsed by `data.json()` call
            });

async function automate_post_data(url = '', data = {}) {
const response = await fetch(url, {
    method: 'POST',
    mode: 'cors', // no-cors, *cors, same-origin
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    //referrerPolicy: 'origin', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
});

if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
}
return response.json();
}

帖子失败:

Access to fetch at 'https://app.automate.mn/api/tools/email/add' from origin 'https://demoautomatemn.wpcomstaging.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
loadForm.js:109 POST https://app.automate.mn/api/tools/email/add net::ERR_FAILED

我希望在 OPTION 调用的响应标头中看到“Access-Control-Allow-Origin”,但什么也没有(Preflight response is not successful)。我已尽一切努力让它发挥作用。

现在欢迎任何建议。

【问题讨论】:

    标签: express http-status-code-406


    【解决方案1】:

    好的,进步但没有雪茄!

    我设置了以下内容:

    在 apache 级别设置:

    https://docs.bitnami.com/bch/infrastructure/nodejs/administration/enable-cors-nodejs/

    您可能还会发现这很有帮助:https://enable-cors.org/server_apache.html

    向请求添加来源

     headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.href
        },
    referrerPolicy: 'origin',
    

    这导致错误消息发生变化:

    Access to fetch at 'https://app.automate.mn/api/tools/email/add' from origin 'https://demoautomatemn.wpcomstaging.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
    

    更新“Content-Type”:“application/x-www-form-urlencoded”,

    根据这篇文章:Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

    我将请求更新为 x-www-form-urlencoded

    const response = await fetch(url, {
            method: method,
            mode: 'cors', // no-cors, *cors, same-origin
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Origin': window.location.href
            },
            referrerPolicy: 'origin', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: data // body data type must match "Content-Type" header
        });
    

    感觉像是进步了,但是我仍然收到 406 错误:

    POST https://app.automate.mn/api/tools/email/add 406
    
    Response {type: "cors", url: "https://app.automate.mn/api/tools/email/add", redirected: false, status: 406, ok: false, …}
    

    【讨论】:

    • 添加在以下标题中,它似乎正在工作'Accept':'application/x-www-form-urlencoded',
    猜你喜欢
    • 2021-09-04
    • 2017-10-12
    • 2021-11-12
    • 2021-01-08
    • 1970-01-01
    • 2023-03-08
    • 2017-05-14
    • 2016-04-15
    • 2019-06-26
    相关资源
    最近更新 更多