skip to Main Content

When sending SignUp and Login data through Postman, it’s getting stored in Mongodb as well as showing success message but when requested through React axios, it is showing error in console as

POST http://localhost:1000/auth/signup 400 (Bad Request)

Below is the backend and frontend code files for reference.

.routes/auth.js

const express = require("express");
const router = express.Router();
const user = require("../models/user");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const {authenticateToken} = require("./userAuth");


router.post("/signup", async(req,res)=>{
    try{
        const {username,password,email} = req.body;
        const hashPass = await bcrypt.hash(password,10);
        const newUser = new user({username:username,email:email,password:hashPass});
        await newUser.save();
        return res.status(200).json({message:"SignUp successful!"})
            }
    
    catch(error){
        res.status(500).json({message:"internal server error"});
    }
});

app.js:

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();
const conn = require("./conn/conn");
app.use(express.json());
app.use(cors({
    origin: 'http://localhost:5173' // Adjust to match your frontend URL
}));

conn().then(() => {
    app.use(express.json());

    app.use("/auth", require("./routes/auth")); 
    // app.use('/user', require("./routes/user"));
    app.listen(process.env.port, () => {
        console.log(`Server started at ${process.env.port}`);
    });
}).catch(error => {
    console.error("Failed to connect to database:", error);
});

Signup.jsx:

`>

import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";


const Signup = () => {
    const [Values,setValues] = useState({
        username: "",password:"",email:"",
    });
    const navigate = useNavigate();
    const change = (e) =>{
        const {name,value} = e.target;
        setValues({...Values,[name]:value});
    }
    const submit = async () => {
        console.log("clicked");
        try {
            if(
Values.username===""||Values.email===""||Values.password===""
            ){alert("All fields are required!");}
            else{    
                const response = await axios.post("http://localhost:1000/auth/signup", 
                Values
                );
                console.log(Values);
                navigate("/login");
            }
        
              
        } catch (error) {
            alert(error.response.data.message);
        }
    };

    return(
     // a simple signup form here to submit signup info.
    );
};

export default Signup;

2

Answers


  1. Chosen as BEST ANSWER

    The given code is correct, the mistake was unrelated to this and was on frontend side while creating form. Also I changed the port number from 1000 to 5500 which worked well on this.


  2. Unfortunately, I can’t leave comments yet. And I had the same issue recently.

    Try to add to your app.use(cors()) the following option: credentials: true.

    This would look like the following:

    const corsOptions = {
      origin: 'http://localhost:5173',
      credentials: true,
    };
    
    app.use(cors(corsOptions));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search