我正在嘗試將影像上傳到 Cloundinary,但是盡管我已將服務器設定為允許所有來源,但與 cors 相關的狀態代碼 500 發生了錯誤。
錯誤資訊是:
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 生成器
uj5u.com熱心網友回復:
也許您應該將內容型別標頭添加到您的 Axios 請求中。像這樣。
const res = await axios.post('url', data, {
headers: {
'content-type': 'application/json'
}
});
uj5u.com熱心網友回復:
從您的客戶端為您的服務器設定代理
代理可以是"proxy": "http://localhost:5000"你的 package.json 中的一個簡單的
,其中所有未知請求都將被代理到 localhost:5000 基本上你需要從客戶端呼叫 api as/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
uj5u.com熱心網友回復:
const cors = require('cors');
var app = express();
app.use(cors());
嘗試這個
uj5u.com熱心網友回復:
這個中間件有助于避免跨平臺錯誤
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
將此標頭中間件設定在 Express 應用程式中所有路由上方的根檔案中,使用 AppJS 中的服務器 cors 塊更新此代碼塊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364658.html
