简体   繁体   English

从客户端向服务器发送提取请求会导致404 Next.js Express

[英]Sending Fetch Request from Client to Server results in 404 Next.js Express

Im trying to figure out some routing issues with express, im using next.js as well but i dont think that is the issues. 我试图找出快递的一些路由问题,我也使用next.js,但是我不认为这是问题。

Originally, i have my clientside POST request pointing to /server , the same with my server.js, which works out fine. 最初,我的客户端POST请求指向/server ,与server.js相同,效果很好。 If i switch it to /api/submit on both client and server, this results in a 404 error. 如果我在客户端和服务器上都将其切换到/api/submit ,则会导致404错误。 I'm sure there is a misconfiguration with my routing in express but i cant seem to figure it out. 我确定快递中的路由配置有误,但我似乎无法弄清楚。 below is my code: 下面是我的代码:

clientside: 客户端:

const submitFormData = e => {
e.preventDefault();
const { formDataOne, formDataTwo } = props;
const formData = {
  formDataOne,
  formDataTwo,
};
fetch('/api/submit', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    data: formData,
  }),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
};

server.js: server.js:

const express = require('express');
const bodyParser = require('body-parser');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    server.use(bodyParser.urlencoded({ extended: true }));
    server.use(bodyParser.json());

    server.post('/api/submit', (req, res) => {
      console.log(req.body);
    });

    server.get('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

You are missing a leading / in your route path: 您在路径中缺少前导/

server.post('/api/submit', (req, res) => {
  console.log(req.body);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM