Reputation: 13
Im trying to figure out some routing issues with express, im using next.js as well but i dont think that is the issues.
Originally, i have my clientside POST request pointing to /server
, the same with my server.js, which works out fine. If i switch it to /api/submit
on both client and server, this results in a 404 error. 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:
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);
});
Upvotes: 0
Views: 334
Reputation: 12071
You are missing a leading /
in your route path:
server.post('/api/submit', (req, res) => {
console.log(req.body);
});
Upvotes: 1