我在heroku上部署了我的nodejs和react应用程序,但是multer upload在localhost
上工作,但在生产中不工作,它给出错误Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
,这是不正确的
const cors = require("cors");
app.use(cors());
app.use("/files", express.static(path.join(__dirname, "public/files")));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public/files");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage: storage }).array("file");
app.post("/upload", function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err);
} else if (err) {
return res.status(500).json(err);
}
return res.status(200).send("files have been uploaded successfully");
});
});
app.listen(process.env.PORT || 8000, () => {
console.log("listening at port 8000");
});
通过react请求发送到/upload
,其中包含所需文件:
const [files, setFiles] = useState([]);
const handleCareer= ()=>{
const data = new FormData();
const pdf = `${Date.now()}${files[0]?.name}`;
const image = `${Date.now()}${files[1]?.name}`;
for (let x = 0; x < files.length; x++) {
data.append("file", files[x]);
}
career.resume = pdf;
career.resumeImage = image;
await fetch("https://shoushapi.herokuapp.com/upload", {
method: "POST",
body: data,
});
}
return (
<form>
...
<div className="row">
<label htmlFor="resumeFile" className="downloadImg">
<AddAPhotoIcon className="postIcon" />
<span>Upload resume</span>
</label>
<input
type="file"
accept="application/pdf,application/msword"
id="resumeFile"
name="file"
className="upload"
onChange={(e) => setFiles([...files, e.target.files[0]])}
></input>
</div>
<div className="row">
<label htmlFor="resumeImage" className="downloadImg">
<AddAPhotoIcon className="postIcon" />
<span>Upload resume image</span>
</label>
<input
type="file"
accept=".png,.jpeg,.jpg"
id="resumeImage"
className="upload"
onChange={(e) => setFiles([...files, e.target.files[0]])}
name="image"
></input>
</div>
<div className="row">
<button type="button" className="btn" onClick={handleCareer}>
Request
</button>
</div>
</form>
代码在开发模式下运行良好,如果我将Access-Control-Allow-Origin
更改为http://localhost:8000
,并将fetch url更改为http://localhost:8000/upload
,则通过在本地运行可以成功上传文件,这里有什么问题?
1条答案
按热度按时间gjmwrych1#
你必须允许你的前端网站url的来源,而不是你的API端点,你可以在cors方法中设置,而不使用头:
或者您可以删除allow origin头并保留cors方法为空,如下所示:
app.use(cors())
,在这种情况下,您将允许所有网站使用您的api。我认为你仍然可以接受从你的localhost前端到你的localhost api的请求的原因,是因为,它们都托管在同一个域中,而且它们都使用同一个代理。