简体   繁体   中英

Register route 404 not found

I am building a register page and when I submit the I am getting a 404 not found. I am using react and express and I think the front end is good. I am missing some back end or have the wrong url for my post request: axios.post('http://localhost:3000/auth'. Would appreciate some advice if anyone can see what I have wrong.

     const handleSubmit = event => {
        event.preventDefault();
        const user = {
          username: username,
          password: password,

        }
        axios.post('http://localhost:5000/', { user })
          .then(res=>{
            console.log(res);
            console.log(res.data);
          })
      }

This is the registerPost function for my route.

export const registerPost = async (req, res) => {
    
    const {username, password} =  req.body;
    
    const newUser = new User({username, password});

    try {
        await newUser.save();
        console.log(newUser);

        res.status(201).json(newUser);
    } catch (error) {
        res.status(409).json({ message: error.message });
    }


}

These are the routes.

import express from 'express';

import { getPosts } from '../controllers/posts.js'
import { createPost, updatePost, deletePost, registerPost } from '../controllers/posts.js'

const router = express.Router();

router.get('/', getPosts);
router.post('/', createPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);
router.post('/auth', registerPost);

export default router;
    

As far as I can see you're passing the following Object from the Frontend:

{ user: { username, password } }

but in the backend you're not looking for the user property, but directly for the username and password.

const {username, password} = req.body
// =>
const { user } = req.body

You're getting a 404 error, which means the url you're trying to reach does not exist. In the React app, you're sending the request at http://localhost:5000/ , but in the Express app, you've defined the register route as /auth .

Updating the url in the React app to http://localhost:5000/auth should fix this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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