Node.JS / Fetch:所请求的资源上没有'Access

编程入门 行业动态 更新时间:2024-10-06 01:37:14

Node.JS / Fetch:所请求的<a href=https://www.elefans.com/category/jswz/34/1770980.html style=资源上没有'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

本文发布于:2024-05-07 11:40:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756076.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源   JS   Node   Fetch   Access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!