![](/img/trans.png)
[英]Axios POST request returns 404 error when sending to Node.js API
[英]POST request to my Node.js server returns 404 in production
我正在通過Axios向我的Node服務器發出POST
API請求,以將string
值發送到我的MongoDB中。
下面的代碼在localhost:8080
在localhost:8080
運行良好,但是當我將代碼推送到Heroku時,請求開始返回404
。 我的節點服務器通過https
運行,並且我已經在其Express框架上配置了CORS。
這是我向節點服務器發出POST
請求時收到的輸出:
POST https://www.mynodeserverurl.com/api/upload-csv 404(未找到)
這是我用於處理此API請求的Node服務器的代碼。
NodeServer / app.js
// Add headers so we can make API requests
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
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);
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
NodeServer /路由/api/api.js
router.post('/upload-csv/', (req, res) => {
let csv = req.body.csv_string.split('$');
let csv_name = csv[0];
let csv_string = csv_name+csv[1];
CSVStore.findOne({url: csv_name})
.then((csv) => {
console.log('IN POST REQUEST');
console.log(csv_string);
return res.status(204).json({msg: 'All good!'});
})
.catch((err) => {
console.log('There was an error!', err);
});
});
向上述路由發出POST
請求甚至不會在節點服務器控制台中顯示console.log()
結果。
這是我對向NodeServer發出POST
請求的Web應用程序的代碼
axios.post(`${utils.fetchURL()}/upload-csv`, {
csv_string: csv_string
})
.then(function(response) {
console.log('Response', response);
return {};
})
.catch(function(error) {
console.log('There was an error!', error);
return {};
});
我發出POST
請求的網址正確,並且csv_string
不為空; 它有數據。
我需要在NodeServer的app.js
進行某種配置以允許在https
上進行CORS嗎?
更新:我可以確認GET
請求有效。 我可以發出GET
請求以從我的MongoDB中檢索string
。 為什么GET
有效而POST
無效?
我遇到了同樣的問題。 我所有的API端點都可以在本地和產品中使用,但是我的一個POST端點可以在生產中使用404,但可以用於GET。
原來,在運行“ git push heroku master”之前,我忘記了上演並提交我的最新更改。 一旦執行完此操作並再次運行“ git push heroku master”,所有內容均已發布並可以在生產環境中使用。
因此,如果您遇到此問題,請嘗試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.