Sun*_*tam 2 javascript api node.js multer axios
我对一个查询感到困惑:当我从运行在不同源的前端调用 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");
})
Run Code Online (Sandbox Code Playgroud)
我的前端代码:假设我正在运行我的index.htmlhttp://127.0.0.1:5500/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>
Run Code Online (Sandbox Code Playgroud)
当我单击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 阻止?
出于 Web 兼容性原因,CORS 不适用于跨源表单帖子。它仅适用于我所说的“动态”请求(例如 AJAX、fetch 和其他一些请求)。
这是因为 HTML 表单早于 CORS 规范。
当引入 CORS 时,他们无法在不破坏现有网站功能的情况下改变这种行为。
以下是更多信息:
MDN 页面列出了受 CORS 约束的请求:哪些请求使用 CORS?
以前的堆栈问题:
如何防止跨站请求伪造 (CSRF) 请求带来的安全问题:
| 归档时间: |
|
| 查看次数: |
1819 次 |
| 最近记录: |