Home > Mobile >  How to fetch data from backend using axios?
How to fetch data from backend using axios?

Time:01-27

I have created a backend server using expressjs. I have created a frontend client using react. But I can't merge them both when am trying to get data from backend using axios am getting an error. This is my index.js from backend

const express=require("express");
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const UserRoute=require("./routes/users");
const AuthRoute=require("./routes/auth");
const PostRoute=require("./routes/posts");
const cors=require('cors');
const app=express();

dotenv.config();
mongoose.connect(process.env.MONGO_URL,{useNewUrlParser: true},()=>{
    console.log("Database connected successfully!!")
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cors());
app.use("/api/user",UserRoute);
app.use("/api/auth",AuthRoute);
app.use("/api/post",PostRoute);



app.listen(8800,()=>console.log("server is running!!"));

This is my posts.js from backend server

const router = require("express").Router();
const User=require("../models/User");
const Post = require("../models/Post");
//create a post
router.post("/", async (req, res) => {
    const newPost = new Post(req.body);
    try {
        const savedPost = await newPost.save();
        res.status(200).json(newPost);
    }
    catch (err) {
        res.status(500).json(err);
    }
});
//update a post
router.post("/:id", async (req, res) => {
    try {
        const post = Post.findById(req.params.id);
        if (req.params.id === req.body.userId) {
            await post.updateOne({ $set: req.body });
            res.status(200).json("The post has been updated!");
        }
        else {
            res.status(403).json("You can update only your post!!");
        }
    }
    catch (err) {
        res.status(500).json(err);
    }
});
//delete a post
router.post("/:id/delete", async (req, res) => {
    try {
        if (req.params.id === req.body.userId) {
            await Post.findByIdAndDelete(req.params.id);
            res.status(200).json("The post has been deleted!!");
        }
        else {
            res.status(403).json("You can delete only your post!!");
        }
    }
    catch (err) {
        res.status(500).json(err);
    }
});
//get a post
router.get("/:id", async (req, res) => {
    try {
        const post = await Post.findById(req.params.id);
        res.status(200).json(post);
    }
    catch (err) {
        res.status(500).json(err);
    }

});
//like a post
router.put("/:id/like", async (req, res) => {
    try {
        const post = await Post.findById(req.params.id);
        if (!post.likes.includes(req.body.userId)) {
            await post.updateOne({ $push: { likes: req.body.userId } });
            res.status(200).json("The post has been liked");
        }
        else {
            await post.updateOne({ $pull: { likes: req.body.userId } });
            res.status(200).json("The post has been disliked");
        }
    }
    catch (err) {
        res.status(500).json(err);
    }

});
//timeline posts
router.get("/timeline/:userId", async (req, res) => {

    try {
        const currentUser = await User.findById(req.params.userId);
        const userPosts = await Post.find({userId:currentUser._id} );
        const friendPosts = await Promise.all(
            currentUser.following.map(friendId => {
               return Post.find({ userId: friendId });
            })
        );
        res.status(200).json(userPosts.concat(...friendPosts));
    }
    catch (err) {
        res.status(500).json(err);
    }
})

module.exports = router;

This is my feed.js from frontend

import "./feed.css";
import Post from "../post/Post";
import Share from "../share/Share";
import { useState } from "react";
import { useEffect } from "react";
import axios from 'axios';

export default function Feed() {
  const [posts,setPosts]=useState([]);
  const [texts,setTexts]=useState([]);
  useEffect(()=>{
    const fetchPosts=async ()=>{
      const res=await axios.get("post/timeline/63c29c2fe9a410383d4bcb98");
      console.log(res);
    };
    fetchPosts();
    
    
  },[])

  return (
    <div className="feed">
      <div className="feedWrapper">
        
        <Share/>
        {/*{Posts.map((p)=>{
          <Post key={p.id} post={p}/>
        })}*/}
      </div>
    </div>
  )
}

When I try to reload the react app it's showing this

GET http://locahost:8800/api/post/timeline/63c29c2fe9a410383d4bcb98 net::ERR_NAME_NOT_RESOLVED
dispatchXhrRequest @ xhr.js:247
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:142
Axios.<computed> @ Axios.js:168
wrap @ bind.js:5
fetchPosts @ Feed.jsx:13
(anonymous) @ Feed.jsx:16
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
(anonymous) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Feed.jsx:15 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

Console Image

CodePudding user response:

API URL is not valid, hostname should be localhost instead of locahost

  • Related