我在 Heroku 上部署了一個 API,當我從我的網站發送 post 請求時,Heroku 日志顯示 method=options 并且不起作用。當我從本地機器發送時,Heroku 日志顯示 method=post 并且一切正常。
我在 StackOverflow Heroku 中發現這篇文章使用 Options 而不是 POST 方法,但該解決方案不能解決我的問題。
Heroku 日志,第一個來自本地,第二個來自網站:
2022-10-06T23:57:19.315699 00:00 heroku[router]: at=info method=POST path="/api/smsNotif/applySmsNotif" host=***** request_id=88da98c7-f136-4775-a52a-b10b104b2cff fwd="****" dyno=web.1 connect=0ms service=11ms status=200 bytes=462 protocol=https
2022-10-07T00:01:05.970299 00:00 heroku[router]: at=info method=OPTIONS path="/api/smsNotif/applySmsNotif" host=***** request_id=039a51c3-a976-47f7-bd03-4c52bc71361f fwd="****" dyno=web.1 connect=0ms service=1ms status=204 bytes=277 protocol=https
我的請求來自托管網站上的 axios:
api({
method: "POST",
url: "/api/smsNotif/applySmsNotif",
data: appData,
});
修復方法=選項的 API 代碼:
const app = express();
app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.use(express.json());
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
// handle OPTIONS method
if ('OPTIONS' == req.method) {
return res.sendStatus(200);
} else {
next();
}
});
uj5u.com熱心網友回復:
處理選項方法僅在沒有 cors 模塊的情況下作業。當您使用 cors 模塊時,您需要進行以下更改。
const app = express();
app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.options('*', cors()) // include before other routes
如果您遇到 CORS 錯誤,請通過洗掉原點和測驗來更改 cors 配置。
app.use(cors())
uj5u.com熱心網友回復:
幾次重新加載后,原始代碼有效,來自(Heroku 使用選項而不是 POST 方法)
謝謝@Dipten
需要注意的一件事是:
app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
我將我的 API 用于多個應用程式,并且我需要在上面的代碼中為 CORS 列出所有這些應用程式。
const app = express();
app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.use(express.json());
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
// handle OPTIONS method
if ('OPTIONS' == req.method) {
return res.sendStatus(200);
} else {
next();
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/518118.html
上一篇:自定義Rails記錄器的方法
