我無法獲取到我的 Express 路由器的 POST 請(qǐng)求。我有許多工作正常的 GET 請(qǐng)求,但這是我的第一個(gè) POST 請(qǐng)求,它不起作用。我的前端代碼如下所示:export async function postHamster(name, age) {try { await fetch('/hamsters/api/new-hamster', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: name, age: age }) }) console.log("postHamster has run") //LOGGED}catch (e) { console.error(e)}}響應(yīng)將始終是:fetchData.js:38 POST http://localhost:3000/hamsters/api/new-hamster 404 (Not Found)我已經(jīng)三重檢查了路徑,它不會(huì)出錯(cuò)。后端路徑是文件“hamsters.js”中的“router.get('api/new-hamster', async (req, res)...”。我還將后端函數(shù)放在其文件的最頂部,以確保它不會(huì)被文件中的任何其他函數(shù)推翻。這是我的 server.js: // THIS FIRST FUNCTION I JUST COPIED FROM A SOLUTION BUT IT DOES NOT SEEM TO HELP// routes/index.jsmodule.exports = (express) => { // Create express Router var router = express.Router(); // add routes server.route('/hamsters/api/new-hamster') .post((req, res) => { res.setHeader('Content-Type', 'application/json'); res.send('You sent: sdadad to Express'); }); return router;}const express = require('express');const server = express();const serverPort = process.env.PORT || 1234;server.use(express.static(__dirname + '/../build'))let data = require('./data.json')const { Router } = require('express');let router = new Router();//USE BODY-PARSER BEFORE REGISTERING ROUTES!const bodyParser = require('body-parser')server.use(bodyParser.urlencoded({ extended: true }));server.use(bodyParser.json())server.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });})
無法 POST 到 Express 路由器(404 錯(cuò)誤)
侃侃爾雅
2022-10-08 17:01:23