资源上没有'Access"/>
Node.JS / Fetch:所请求的资源上没有'Access
即使我的服务器端代码看起来像这样,也会收到错误消息“ No'Access-Control-Allow-Origin'header”:
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!")
})
这里是产生错误的客户端代码:
fetch(`/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);
});
请注意,服务器位于.js中>
即使我的服务器端代码看起来像这样,也会收到错误消息“ No'Access-Control-Allow-Origin'header”:const express = require('express'); //使express可用const app = express(); // ...
回答如下:您可以通过“ npm i cors”安装cors来使用类似的cors模块
更多推荐
Node.JS / Fetch:所请求的资源上没有'Access
发布评论