【发布时间】:2020-12-26 04:08:59
【问题描述】:
我正在尝试将表单数据发送到 api,并且当我向 api 发送请求时,我能够在前端对接上获取数据,但我遇到了一个我无法解决的错误,这是代码我将数据发送到 api 的 js
const value = {
name: document.getElementById("name").value,
designation: document.getElementById("designation").value,
companyName: document.getElementById("companyName").value,
email: document.getElementById("email").value,
phoneNumber: document.getElementById("phoneNumber").value,
pinCode: document.getElementById("pinCode").value,
location: document.getElementById("location").value,
message: document.getElementById("message").value,
};
const formReset = document.getElementById("contactForm");
formReset.reset();
const data = JSON.stringify(value);
console.log(data);
console.log(value.email);
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
let requestOptions = {
method: "POST",
headers: myHeaders,
body: JSON.stringify(value),
redirect: "follow",
};
fetch(
"https://us-central1-gmbexample-f23ef.cloudfunctions.net/api/forms",
requestOptions
)
.then((response) => response.text())
.then((result) => {
console.log(result);
alert(
"Your form has been submitted successfully."
);
})
.catch((error) => console.log("error", error));
这里是我如何处理后端请求
const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config();
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With",
"Content-Type",
"Accept"
);
});
app.use(bodyParser.urlencoded({ extended: true }));
// URL => /api/reports (PUT)
// .put("/reports", reportsServer);
app.post("/forms", async (req, res) => {
console.log(req.body);
res.status(200).send("oj");
});
exports.api = functions.https.onRequest(app);
我得到的错误是 CORS 策略已阻止从源“https://gmbexample-f23ef.firebaseapp.com”访问“https://us-central1-gmbexample-f23ef.cloudfunctions.net/api/forms”获取:对预检的响应请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
任何人都可以提出任何解决方案
【问题讨论】:
-
解决方法在错误中。服务器必须提供“Access-Control-Allow-Origin”标头。时期。就是这样。
-
@gforce301 我在后台添加
-
res.header接受 2 个字符串field, value或包含标头的 JSON 对象作为key-value对。请将第二次呼叫修复为res.header并检查 -
@KunalKukreja 是否可以为特定请求应用 cors 规则,例如在我的情况下,我只想为 /forms 应用 cors,我正在尝试您建议的解决方案
-
@Amar 你可能想使用这个:npmjs.com/package/cors#enable-cors-for-a-single-route。这将为您省去所有的麻烦
标签: javascript node.js express cors