反应不从节点后端获取数据

时间:2020-06-03 05:22:31

标签: node.js reactjs express ecmascript-6 fetch

我正在学习Node.JS,并使用React从Node.JS的后端获取数据。 我在Postman中测试了Express的API,并且运行良好。但是,当我使用提取API时,它没有将结果存储在Hooks中,也没有给出错误。我正在尝试使用React显示存储在Mongodb数据库中的Upvotes数量。我没有任何错误。 React正在打印在useState中传递的原始数据。这是我的代码:

import React, {useState, useEffect} from "react";
import articles from "./Content";
import { Link } from "react-router-dom";
import ArticleList from "../components/ArticleList";

const Articles = ({ match }) => {
  const name = match.params.name;

  const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });
  //fetching url name/handle from the articles Route path



  useEffect(() => {

fetch(`http://localhost:5000/api/articles/${name}`,{ mode: 'no-cors' })
.then(res => res.json())
.then(
  (result) => {
    setArticleInfo(result)
    console.log("result"+result)
  },
  // Note: it's important to handle errors here
  // instead of a catch() block so that we don't swallow
  // exceptions from actual bugs in components.
  (error) => {
   console.log(error);
    });
  }
)

  console.log("after use effect"+articleInfo);
  //Return name if url path matches the name of the article
  const foundArticle = articles.find((article) => article.name === name);
  //display articles except the current one
  const otherArticles = articles.filter((article) => article.name !== name);

  return (
    <div>
      {foundArticle ? (
        <div>
          <p>Total likes: {articleInfo.upvotes}</p>
          <h2>{foundArticle.title}</h2>
          <p>{foundArticle.content}</p>

          <Link className="btn" to="/articles-all">
            All blog
          </Link>
        </div>
      ) : (
        <h4>Not found</h4>
      )}
      <ArticleList articles={otherArticles} />
    </div>
  );
};
export default Articles;

Server.js

const express = require("express");
const bodyParser = require("body-parser");
const MongoClient = require("mongodb");
const app = express();

app.use(bodyParser.json());

app.get("/api/articles/:name", async (req, res) => {
  try {
    const articleName = req.params.name;

    // Establishing connection with local MongoDB
    const client = await MongoClient.connect("mongodb://localhost:27017", {
      useNewUrlParser: true,

    });
    const db = client.db("blogapp");

    //Finding url param in the db
    const articleInfo = await db
      .collection("articlesdb")
      .findOne({ name: articleName });
    res.status(200).json(articleInfo);

    client.close();
  } catch (error) {
    res.status(500).json({ message: "Error connecting to db", error });
  }
});
//For likes
app.post("/api/articles/:name/likes", async (req, res) => {
  try {
    const articleName = req.params.name;
    const client = await MongoClient.connect("mongodb://localhost:27017", {
      useNewUrlParser: true,
    });
    const db = client.db("blogapp");
    const foundArticle = await db
      .collection("articlesdb")
      .findOne({ name: articleName });
    const addLikes = foundArticle.upvotes + 1;
    const updateLikes = { $set: { upvotes: addLikes } };
    await db
      .collection("articlesdb")
      .updateOne({ name: articleName }, updateLikes);

    const updated = await db
      .collection("articlesdb")
      .findOne({ name: articleName });
    res.status(200).json(updated);
    client.close();
  } catch (error) {
    res.status(500).send("update failed");
  }
});

//For comments
app.post("/api/articles/:name/comment", async (req, res) => {
  try {
    const { user, text } = req.body;
    const articleName = req.params.name;
    const client = await MongoClient.connect("mongodb://localhost:27017", {
      useNewUrlParser: true,
    });
    const db = client.db("blogapp");

    const foundName = await db
      .collection("articlesdb")
      .findOne({ name: articleName });
    const store = foundName.comments.concat(user, text);
    const addComment = { $set: { comments: store } };

    const update = await db
      .collection("articlesdb")
      .updateOne({ name: articleName }, addComment);
    const show = await db.collection("articlesdb").findOne({ name: articleName });

    res.status(200).json(show);
    client.close();
  } catch (error) {
    res.status(500).send("update failed");
  }

  // res.status(200).send(articlesinfo[articleName].comments);
});
app.listen(5000, () => console.log("listening on port 5000"));

Mongodb中的数据:

{
        "_id" : ObjectId("5ed7295fdba52a9d584c0453"),
        "name" : "learn-react",
        "upvotes" : 3,
        "comments" : [ ]
}
{
        "_id" : ObjectId("5ed7295fdba52a9d584c0454"),
        "name" : "learn-node",
        "upvotes" : 10,
        "comments" : [ ]
}
{
        "_id" : ObjectId("5ed7295fdba52a9d584c0455"),
        "name" : "learn-cv",
        "upvotes" : 2,
        "comments" : [ ]
}

0 个答案:

没有答案