mongoose 如何使用axios从后端获取数据?

ldxq2e6h  于 2023-01-21  发布在  Go
关注(0)|答案(1)|浏览(119)

我用expressjs创建了一个后端服务器,我用react创建了一个前端客户端,但是当我试图用axios从后端获取数据时,我无法合并它们,我得到了一个错误。这是我从后端获取的index.js

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!!"));

这是我的posts.js从后端服务器

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;

这是我从前端得到的feed.js

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>
  )
}

当我尝试重新加载react应用程序时,它会显示以下内容

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

e5njpo68

e5njpo681#

API URL无效,主机名应为localhost而不是locahost

相关问题