'POST route not found, React and express
When trying to use the sign-up route I have the following error : POST http://localhost:3001/sign-up 404 (Not Found)
I went through similar question on StackOverflow but didn't find where my problem came from...
In the frontend part I'm fetching the POST route 'sign-up' but it seems it can't find it while in the back I have the same name for the route POST, all is well imported in the app.js in back. I check everything I knew and still haven't find a solution.
Here's part of my code, let me know if you need anything else.
React : Home.js
import React, {useState} from 'react';
function Home(props) {
const [signUpEmail, setSignUpEmail] = useState('')
var handleSubmitSignup = async () => {
const data = await fetch('/sign-up', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `email=${signUpEmail}`
})
}
return (
<Box>
<Input onChange={(e) => setSignUpEmail(e.target.value)}/>
<Button onClick={() => handleSubmitSignup()}>
Sign-up
</Button>
</Box>
);
}
export default Home
Express : app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
require('./models/connection')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'reactapp/build')));
app.use('/', indexRouter);
app.use(function(req, res, next) {
next(createError(404));
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Express/routes: index.js
var express = require('express');
var router = express.Router();
var userModel = require('../models/users')
router.post('/sign-up', async function(req,res,next){
var newUser = new userModel({
email: req.body.email,
})
saveUser = await newUser.save()
}
res.json({saveUser})
})
module.exports = router;
Thanks for your help !
Solution 1:[1]
In your app.js you are defining your user router like this
app.use('/users', usersRouter);
If you do this, then your route would be http://localhost:3001/users/sign-up not
http://localhost:3001/sign-up. That's why you are getting 404 error
In your react app update
const data = await fetch('users/sign-up', { /* Rest of the code */ })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shivam |
