我正在尝试上传图像到Cloundinary,但是出现了一个错误,状态码500与cors相关,尽管我已经将服务器设置为允许所有来源。
错误消息为:
POST http://localhost:5000/my-route-upload 500 (Internal Server Error)
下面是我的POST函数:
const cloudinaryUpload = (fileToUpload) => {
return axios.post(API_URL + '/cloudinary-upload', fileToUpload)
.then(res => console.log(res))
.catch(err => {
console.log(err)
console.log("cannot post")
}); }
在服务器端,我在App.JS中添加了以下代码块
const cors = require('cors');
var app = express();
app.use(cors({
origin: "*",
})
);
这些代码确实执行了,我试着将原始代码修改为特定的代码,比如http://127.0.0.1:3001 (我的客户端端口是3000)。然后出现了另一条错误消息
返回到选项卡Network/Headers中的第一个错误:
Request URL: http://localhost:5000/cloudinary-upload
Request Method: POST
Status Code: 500
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: *
Host: localhost:5000
Origin: http://127.0.0.1:3000
我不知道为什么它不起作用。我对客户端使用create-react-app,对服务器使用Express生成器
发布于 2021-11-24 04:17:26
也许您应该将content-type头添加到Axios请求中。就像这样。
const res = await axios.post('url', data, {
headers: {
'content-type': 'application/json'
}
});
发布于 2021-11-24 05:04:58
从客户端为服务器设置代理
Proxy可以是你的package.json中的一个简单的"proxy": "http://localhost:5000"
,所有未知的请求都会被代理到localhost:5000基本上你需要从客户端调用这个package.json作为/my-route-upload
而不是http://localhost:5000/my-route-upload
。
但更好的方法是添加一个名为src/setupProxy.js
的文件,并将$ npm install http-proxy-middleware --save
添加到该文件中
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};```
Also look at enabling cors in express
https://enable-cors.org/server_expressjs.html
发布于 2021-11-24 07:02:39
const cors = require('cors');
var app = express();
app.use(cors());
尝尝这个
https://stackoverflow.com/questions/70090579
复制相似问题