I have been trying to get the response from the server but it shows error. I’m using vs code for this program. When I check the "process.env.MONGO_URL" using console.log() ,it says undefined. (It worked untill yesterday)
and when check the network in inspect mode in chrome, for register page , it shows
xhr.js:247 POST http://localhost:5173/register 404 (Not Found)
dispatchXhrRequest @ xhr.js:247
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:142
httpMethod @ Axios.js:181
wrap @ bind.js:5
registerUser @ RegisterPage.jsx:11
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
settle.js:19 Uncaught (in promise) AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
The network page shows
Request URL: http://localhost:5173/register
Request Method: POST
Status Code: 404 Not Found
Remote Address: [::1]:5173
Referrer Policy: strict-origin-when-cross-origin
Register page
import { Link } from "react-router-dom";
import axios from "axios"
import { useState } from "react";
export default function RegisterPage(){
const [name,setName] = useState('');
const [email,setEmail] = useState('');
const [password,setPassword] = useState('');
function registerUser(ev){
ev.preventDefault();
axios.post('http://localhost:5173/register',{
name,
email,
password
});
}
return (
<div className="mt-4 grow flex items-center justify-around">
<div className="mb-32">
<h1 className="text-4xl py-4 text-center mb-4" >Register</h1>
<form className="max-w-md mx-auto" onSubmit={registerUser}>
<input type="text" placeholder="your name"
value={name} onChange={
ev =>setName(ev.target.value)}>
</input>
<input type='email'placeholder="[email protected]"
value={email} onChange = {
ev =>setEmail(ev.target.value)}>
</input>
<input type='password' placeholder="password"
value={password} onChange= {
ev=>setPassword(ev.target.value)}>
</input>
<button className="primary">Register</button>
<div className="text-center p-3 text-gray-500">
Already have an account?
<Link className="underline text-black"
to={"/login"}>login</Link>
</div>
</form>
</div>
</div>
);
}
index.js page
const express = require("express")
const cors = require("cors")
const bcrypt = require('bcryptjs')
require('dotenv').config({debug : true})
const User = require('./models/User.js')
const app = express()
const mongoose = require('mongoose')
mongoose.set('strictQuery', true);
const bcryptSalt = bcrypt.genSaltSync(10);
app.use(express.json());
app.use(cors({
credentials:true,
origin: 'http://localhost:5173',
}));
console.log(process.env.MONGO_URL)
mongoose.connect(process.env.MONGO_URL);
app.get('/test',(req,res)=>{
res.json("test done")
})
app.post('/register', async (req,res)=>{
const {name,email,password} = req.body;
const userDoc = await User.create({ /*User = usermodel userDoc = user created user*/
name,
email,
password:bcrypt.hashSync(password,bcryptSalt),
})
res.json(userDoc)
})
app.listen(3000);
User.js page
const mongoose = require('mongoose');
const {Schema} = mongoose;
const UserSchema = new Schema({
name: String,
email:{ type:String,
unique:true},
password :String,
});
const UserModel = mongoose.model('User',UserSchema)
module.exports = UserModel;
it is app.jsx
import './App.css'
import {Route,Routes} from "react-router-dom";
import IndexPage from './pages/IndexPage';
import LoginPage from './pages/LoginPage';
import Layout from './Layout';
import RegisterPage from './pages/RegisterPage';
import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:3000';
axios.defaults.withCredentials = true;
function App() {
return (
<Routes>
<Route path="/" element={<Layout/>}>
<Route index element = {<IndexPage/>} />
<Route path="/login" element={<LoginPage/>}/>
<Route path="/register" element={<RegisterPage/>}/>
</Route>
</Routes>
)
}
export default App
2
Answers
Since you are running your server on port 3000, But in your client you are using port 5173 to post your request.
To make it work, you need to post your register request on
localhost:3000/register
and pass withCredentials flag true along with you requestindex.js
Register Page
I suspect that your backend server run on different port since React runs on port
:3000
by default so change your backend server’s port. In index.js of backend code changeapp.listen(3000)
toapp.listen(5000)
Now you can request your api in react as below
and don’t forget to configure cors
app.use(cors())
in index.js