[英]Node.JS/Fetch: No 'Access-Control-Allow-Origin' header is present on the requested resource
I receive the error "No 'Access-Control-Allow-Origin' header" even though my server-side code looks like this:我收到错误“没有‘Access-Control-Allow-Origin’标头”,即使我的服务器端代码如下所示:
const express = require('express'); //make express available
const app = express(); //invoke express
const multer = require('multer') //use multer to upload blob data
const upload = multer(); // set multer to be the upload variable (just like express, see above ( include it, then use it/set it up))
const fs = require('fs'); //use the file system so we can save files
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin");
next();
});
app.post('/upload', upload.single('data'), function (req, res, next) {
console.log(req.file_name); // see what got uploaded
fs.writeFileSync(req.file_name, Buffer.from(new Uint8Array(req.data))); // write the blob to the server as a file
res.sendStatus(200); //send back that everything went ok
})
//serve out any static files in our public HTML folder
// app.use(express.static('public'))
//makes the app listen for requests on port 3000
app.listen(3000, function(){
console.log("app listening on port 3000!")
})
Here is the client-side code that yields the error:这是产生错误的客户端代码:
fetch(`https://www.eartrainer.app/upload/`,
{ method: "POST", body: formdata, // with our form data packaged above
headers: new Headers({ 'enctype': 'multipart/form-data',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin'})
}).then(response => {
if (response.ok) return response;
else throw Error(`Server returned ${response.status}: ${response.statusText}`);
}).then(response => console.log(response.text()))
.catch(err => {
alert(err);
});
Please note, the server is in app.js located here at https://www.example.com/upload/请注意,服务器位于 app.js 中,地址为https://www.example.com/upload/
You can use the cors module.您可以使用cors模块。 Install though npm...
通过 npm 安装...
$ npm i cors
const cors = require('cors');
app.use(cors());
Check out Cross-Origin Resource Sharing (CORS) for more information查看跨源资源共享 (CORS)以获取更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.