我无法获取到我的 Express 路由器的 POST 请求。我有许多工作正常的 GET 请求,但这是我的第一个 POST 请求,它不起作用。我的前端代码如下所示: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)}}响应将始终是:fetchData.js:38 POST http://localhost:3000/hamsters/api/new-hamster 404 (Not Found)我已经三重检查了路径,它不会出错。后端路径是文件“hamsters.js”中的“router.get('api/new-hamster', async (req, res)...”。我还将后端函数放在其文件的最顶部,以确保它不会被文件中的任何其他函数推翻。这是我的 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(); });})
添加回答
举报
0/150
提交
取消