【问题标题】:why my formdata POST isn't blocked by Cors policy?为什么我的 formdata POST 没有被 Cors 政策阻止?
【发布时间】:2021-10-11 00:07:30
【问题描述】:

我对一个查询感到困惑:当我从运行在不同来源的前端调用 POST 请求到在不同来源运行的后端时,为什么我的包含表单数据的 POST 请求没有被 CORS 策略阻止??

我的 Nodejs 代码包含以下代码行:

const express = require('express');
const app = express();
const path = require("path");
const multer = require('multer');
const upload = multer({
    dest:"uploads/"
})
app.use("/image",express.static(path.join(__dirname,"uploads")))
app.post("/upload",upload.single('profile'),(req,res)=>{
    console.log(req.body);
    console.log(req.file);
    res.send("uploaded");
})

app.listen(8080,(err)=>{
    if (err) {
        console.log("Opps");
    }
},()=>{
    console.log("listening at port 8080");
})

我的前端代码: 假设我从 http://127.0.0.1:5500/index.html 运行我的 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Form with Photos</title>
</head>
<body>
    
    <form onsubmit="handleForm(event)">
        <input type="text" name="username"> <br>
        <input type="file" name="profile"> <br>
        <button type="submit">Submit</button>
    </form>
   
    <script>
        const handleForm =(e)=>{
          let username = document.querySelector("input[name='username']");
          let profile = document.querySelector("input[name='profile']");
          let fd = new FormData();
          fd.append("username",username.value);
          fd.append("profile",profile.files[0]);
          axios({
              method:"post",
              url:"http://localhost:8080/upload",
              data:fd
          }).then((response)=>{
              console.log(response.body);
          }).catch((e)=>{
              console.log(e);
          })
     
          e.preventDefault();
        }
    </script>
</body>
</html>

当我点击submit button, my files and input are successfully submitted to my backend. But I am wondering my server http://localhost:8080 and client:http://127.0.0.1:5500/index.html is different origins. But why CORS didn't block this post request? Note:我只是很想知道表单数据是否发布通过 API 的请求是否被 CORS 阻止?`

【问题讨论】:

  • 您不需要在同一个域中提交 POST 请求;您可以将数据发布到任何地方。

标签: javascript node.js api axios multer


【解决方案1】:

出于网络兼容性的原因,CORS 不适用于跨域表单帖子。它仅适用于我所说的“动态”请求(例如 AJAX、fetch 和其他一些)。

这是因为 HTML 表单早于 CORS 规范。

引入 CORS 后,他们无法在不破坏现有网站功能的情况下更改此行为。

这里有更多信息:

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2020-06-29
    • 2018-03-22
    • 2020-07-29
    • 2021-09-17
    • 2019-12-19
    • 2020-11-15
    • 2020-04-07
    • 2021-06-13
    相关资源
    最近更新 更多