0

I am new to web development. I have created a database using mongoose and express(Rest API). I want to connect this with my client folder, which is the front-end part. But I am getting errors. This is my user.js from the backend.

const User=require("../model/User");
const router= require( "express").Router();

router.post("/",async (req,res)=>{
    try{
        const newUser=new User({
            name: req.body.name,
            age:req.body.age
        });
        const user=await newUser.save();
        res.status(200).json("Account activated");
    }
    catch(err){
        res.status(400).json(err);
    }
    
});
router.get("/:id",async (req,res)=>{
 
        try{
            const user=await User.findById(req.params.id);
            res.status(200).json(user.name);
         }
         catch(err){
             res.status(500).json(err);
         }
    }
    
)
module.exports =router;

This is my index.js from backend

const express =require( 'express');
const mongoose =require('mongoose');
const dotenv =require( "dotenv");
const UserRoute=require("./routes/user");
const app=express();
dotenv.config();
mongoose.connect(process.env.MONGO_URL,{useNewUrlParser: true},()=>{
    console.log("Database connected successfully!!")
});
app.use(express.json())
app.use("/register",UserRoute);


app.listen(8000,()=> console.log("Server connected!!!"));

This is my User component from the front-end

import React from 'react';
import { useEffect } from 'react';
import axios from 'axios';

export default function User() {
    useEffect(()=>{
        const fetchPosts=async ()=>{
          const res=await axios.get("register/63cac1881a41912c72d734c6");
          console.log(res);
        };
        fetchPosts();
      },[])
    
  return (
    <div>
      <input type="text" placeholder='Enter your name....'/>
      <input type="text" placeholder='Enter your age....' />
    </div>
  )
}

And am getting an error like thisConsole error

  • Have you noticed your react app is running on port 3000, and node app is running on port 8000? And without specifying the full url to the API - your axios on frontend is trying to load something from port 3000 instead of 8000? – Sergey Sosunov Jan 20 '23 at 17:40
  • Yes, yes I noticed it. But i don't know how to change it!! – Robert Downey Jr. Jan 20 '23 at 17:46
  • Just specify the full url. Change `axios.get("register/63cac1881a41912c72d734c6");` to `axios.get("http://localhost:8000/register/63cac1881a41912c72d734c6");`. Or utilize axios [baseURL](https://stackoverflow.com/questions/64798213/how-to-configure-axios-base-url) – Sergey Sosunov Jan 20 '23 at 17:51
  • If I change axios.get("register/63cac1881a41912c72d734c6"); to axios.get("http://localhost:8000/register/63cac1881a41912c72d734c6"); i get Access to XMLHttpRequest at 'http://localhost:8000/register/63cac1881a41912c72d734c6' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:247 GET http://localhost:8000/register/63cac1881a41912c72d734c6 net::ERR_FAILED 200 (OK) dispatchXhrRequest @ xhr.js:247 xhr @ xhr.js:49 User.jsx:10 – Robert Downey Jr. Jan 20 '23 at 17:56
  • Well that means you finally hit your API server, and your server needs some [CORS](https://stackoverflow.com/a/45049763/5767872) tweaks now – Sergey Sosunov Jan 20 '23 at 17:59
  • Now am getting two replies instead of one. How to stop re rendering the useEffect – Robert Downey Jr. Jan 20 '23 at 18:05
  • If you are using `` - that will work in that way, but only in development. Docs: [click](https://reactjs.org/docs/strict-mode.html). Additionally: this [post](https://stackoverflow.com/a/60619061/5767872) – Sergey Sosunov Jan 20 '23 at 18:07

0 Answers0