从客户端向 Express 服务器发送 POST 请求时出现 CORS 错误

问题描述 投票:0回答:1

当我尝试将表单从我的网站提交到我的 Express 服务器时,出现 CORS 错误。这是设置和问题:

服务器(快速)代码:

const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors({
  origin: 'https://www.teckwithfeya.com'
}));
app.use(express.json());

app.post("/send", (req, res) => {
  console.log(req.body); // Log the received data
  res.send("Form submitted successfully");
});

app.listen(7000, () => {
  console.log("Server is running on port 7000");
});

客户端 JavaScript:

document.addEventListener("DOMContentLoaded", function () {
  const contactForm = document.getElementById("contactForm");
  contactForm.addEventListener("submit", function (event) {
    event.preventDefault();

    const formData = new FormData(contactForm);
    fetch("https://www.teckwithfeya.com/send", {
      method: "POST",
      body: formData
    })
    .then(response => response.text())
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.error("Error:", error);
    });
  });
});

当我提交表单时,我在浏览器控制台中收到以下 CORS 错误:

从源“https://www.teckwithfeya.com”获取“https://www.teckwithfeya.com/send”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经使用 cors 中间件在我的 Express 服务器上设置了 CORS。 我尝试使用 JSON 和 FormData 进行 fetch。

javascript node.js cors fetch-api
1个回答
0
投票

确保您已获得授权。

const express = require("express");
const cors = require("cors");

const app = express();

app.use(cors({
  origin: 'https://www.teckwithfeya.com',
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());

app.options('/send', cors()); // Enable preflight for /send

app.post("/send", (req, res) => {
  console.log(req.body); // Log the received data
  res.send("Form submitted successfully");
});

app.listen(7000, () => {
  console.log("Server is running on port 7000");
});

客户端代码-

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Submission</title>
</head>
<body>
  <form id="contactForm">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <button type="submit">Submit</button>
  </form>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const contactForm = document.getElementById("contactForm");
      contactForm.addEventListener("submit", function (event) {
        event.preventDefault();

        const formData = new FormData(contactForm);
        fetch("https://www.teckwithfeya.com/send", {
          method: "POST",
          body: formData
        })
        .then(response => response.text())
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error("Error:", error);
        });
      });
    });
  </script>
</body>
</html>

我想这些变化是不言自明的。让我知道它是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.