使用axios / fetch从Node到React获取数据

huangapple go评论72阅读模式
英文:

Using axios / fetch to fetch data from node toreact

问题

我明白你的问题。以下是有关如何从Node后端到React前端获取数据的问题的翻译部分:

在你的React代码中,你尝试了两种方法来从Node后端获取数据,但遇到了问题。

第一种方法出现了401未授权错误,这可能是因为你的请求没有正确的身份验证。你需要确保在请求中包括有效的身份验证令牌(token)。你可以检查你的身份验证逻辑,确保令牌被正确设置并发送到后端。

第二种方法没有在控制台中返回任何内容,这可能是因为你没有正确地处理响应。在你的fetchData函数中,你可以尝试以下修改:

const fetchData = async () => {
  try {
    const response = await fetch("http://localhost:4000/api/jobs", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Origin": true,
        credentials: "same-origin",
        Authorization: `Bearer ${token}`,
      },
    });

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    const newData = await response.json();
    console.log(newData);
    setName(newData.jobs.name);
  } catch (error) {
    console.error("Fetch error:", error);
  }
};

fetchData();

这个修改将首先检查响应是否成功,如果不成功,则抛出一个错误。这有助于更好地处理错误情况并提供更多的信息来调试问题。

请确保在使用第二种方法时,你的token变量已经被定义和设置为有效的身份验证令牌。

希望这些修改能帮助你解决问题,成功获取数据从后端到前端。如果你需要进一步的帮助,请提供更多的信息。

英文:

Please I need a help on how to fetch a data from node to react, I have been stuck here for 2 weeks now.

Here are my backend code:

server.js:

require("dotenv").config();


const app = require("./src/app");

const port = process.env.PORT || 4000;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Server is running on port http://localhost:${port}`);
});

app.js:

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();
app.use(
  cors({
    origin: ["http://localhost:4000/api", "http://localhost:3000"],
  })
);
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use(express.json());
app.use(express({ type: "application/vnd.api+json" }));
app.use(express.urlencoded({ extended: true }));
app.use(
  cookieSession({
    name: process.env.COOKIE_NAME, //ookie name in .env
    secret: process.env.COOKIE_SECRET, //secret name in .env
    httpOnly: true,
    sameSite: "strict",
    maxAge: 24 * 60 * 60 * 1000, // 24 hours duration before expire
  })
);

app.use("/uploads", express.static("uploads"));

const jobRoute = require("./routes/job.routes");
app.use("/api/", jobRoute);

module.exports = app;

service.js:

const db = require("../config/database");
const notificationServices = require("./notification.services");
const { jobReuseQuery } = require("../job reuseable query/job.queries");

const createJob = async (body) => {
  const {
    title,
    salary_type,
    salary,
    job_types,
    description,
    company_id,
    sector_id,
    category_id,
  } = body;

  const { rows } = await db.query(
    `INSERT INTO jobs (title, salary_type, salary, job_types, description, company_id, sector_id, category_id) 
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`,
    [
      title,
      salary_type,
      salary,
      job_types,
      description,
      company_id,
      sector_id,
      category_id,
    ]
  );
  notificationServices.sendMatchJobsToUserProfiles(rows[0]);

  return rows[0];
};


const getAllJobs = async () => {
  const { rows } = await db.query("SELECT * FROM jobs");

  return rows;
};

controller.js:

const jobService = require("../services/job.services");

const createJob = async (req, res) => {
  try {
    const job = await jobService.createJob(req.body);
    res.status(201).send({
      message: "Job created successfully",
      data: job,
    });
  } catch (err) {
    res.status(400).send(err.message);
  }
};

const getAllJobs = async (req, res) => {
  try {
    const jobs = await jobService.getAllJobs();
    res.status(200).send({ data: jobs });
  } catch (err) {
    res.status(400).send({ message: err.message });
  }
};

routes.js:

const router = require("express-promise-router")();
const jobController = require("../controllers/job.controller");
const auth = require("../middleware/auth.middleware");

router.post("/jobs", auth, jobController.createJob);

auth.js:

const db = require("../config/database");
const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
dotenv.config();

const auth = async (req, res, next) => {
  const token = req.session.token;

  if (!token) {
    return res.status(401).send({ error: "Please Authenticate" });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    const { rows } = await db.query("SELECT * FROM users WHERE id = $1", [
      decoded.id,
    ]);

    if (!rows[0]) {
      throw new Error("User not found");
    }
    req.user = rows[0];
    
    next();
  } catch (error) {
    return res.status(401).send({ error: error.message });
  }
};

module.exports = auth;

React frontend code:

import React, { useEffect } from "react";
import tech from "../../image/tech-big.svg";
import health from "../../image/health-big.svg";
import eng from "../../image/eng-big.svg";
import axios from "axios";
import { useState } from "react";

const Joblist = () => {
  const [name, setName] = useState([]);

  //first method
  const response = axios
    .get("http://localhost:4000/api/jobs/")
    .then((res) => res.json());
  console.log(response);

  //second method
  const fetchData = async () => {
    const newData = await fetch("http:localhost:4000/api/jobs", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        ACCEPT: "application/json",
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Origin": true,
        credentials: "same-origin",
        Authorization: `Bearer ${token}`,
      },
    }).then((res) => res.json());
    console.log(newData);
    setName(newData.jobs.name);

    fetchData();
  };

you can see in my react, I have 2 method i used trying to fetch the data fron node to the react

first method return error in my browser console :

Promise {<pending>}
GET http://localhost:4000/api/jobs/ 401 (Unauthorized)
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

while the second method return nothing in my browser console

I am trying to fetch a data from my node backend into frontend react but my first method log error while the second method log nothing

答案1

得分: 0

我认为你需要稍微清理一下你的设置,因为你正在使用CORS,你可以首先进行一些更改:

// .....
const app = express();

// 使用CORS,你可以在同一个地方进行所有设置,所以不需要设置头信息
const corsOptions = {
    origin: ["http://localhost:4000/api", "http://localhost:3000"],
    methods: "GET, POST, PUT, DELETE, OPTIONS, HEAD",
    credentials: true,  // 用于JWT/cookie!         
};
app.use(cors(corsOptions));

app.use(express.json());
app.use(express({ type: "application/vnd.api+json" }));
app.use(express.urlencoded({ extended: true }));
app.use(
  cookieSession({
        name: process.env.COOKIE_NAME,
        secret: process.env.COOKIE_SECRET, 
        maxAge: 24 * 60 * 60 * 1000,
        httpOnly: true,
        sameSite: false, //如果部署到跨域生产环境,请设置为"None"。
        secure: false,  //如果在https的生产环境中需要,请设置为true
   });
);

app.use("/uploads", express.static("uploads"));

const jobRoute = require("./routes/job.routes");
app.use("/api/", jobRoute);

module.exports = app;

更新fetch部分,我进行了清理(删除了头信息),我注意到你在job.controller.js中将数据属性放在了响应JSON中,所以你需要再次检查你的数据库结构是否正常工作。

useEffect(() => { 
  const fetchData = async () => {
      try {
          const response = await fetch("http:localhost:4000/api/jobs", {
             credentials: "include", //以便能够发送带有cookies的请求...
          });
          if(response.ok) {
              const newData = await response.json();
              console.log(newData);
              setName(newData.data.jobs.name); //这部分你需要再次检查你的数据结构...
          }
      } catch (error) {
          console.log(error)
      }
  }  
  fetchData();
}, []);

可选注意事项:这部分不是你的问题的一部分,只是以防cookie-session和JWT令牌仍然存在问题,你可以更改JWT在cookie中的存储方式:cookie-session的目的是创建一个“会话ID”,通过在客户端(浏览器)上存储它(在cookie中)来进行用户身份验证,如果你要使用JWT令牌进行身份验证,我真的看不出为什么要使用它?如果你在这部分仍然遇到问题,你可以查看下面的步骤:

首先,你可能需要安装cookie-parser中间件,因为如果这种方法对你有效,你将能够卸载cookie-session。

const cookieParser = require('cookie-parser')
// ...
app.use(cookieParser());

在auth.controllers.js中:

const loginAuth = async (req, res) => {
    try {
        const token = await authServices.login(req.body);
        // 在cookie中设置JWT令牌
        res.cookie("jwt", token, {
            maxAge: 24 * 60 * 60 * 1000,
            httpOnly: true,
            sameSite: false, //如果部署到跨域生产环境,请设置为"None"。
            secure: false,  //如果在https的生产环境中需要,请设置为true
        }) 
        return res.status(200).json({
            //如果发送的请求体匹配,控制器将返回此消息
            message: "用户登录成功!",
        });
    } catch (error) {
        //否则将返回此错误消息
        return res.status(500).json({ message: error.message });
    }
};

// 为用户创建注销会话,将会话签名为空
const logoutAuth = async (req, res) => {
    res.clearCookie("jwt")
    return res.status(200).send({ message: "用户成功登出!" });
};

还需要在activeAuth函数中替换const token = req.session.token;,在auth.middleware.js的auth中间件函数中替换为:

const token = req.cookies["jwt"]  //或者
const token = req.cookies.jwt

最后,如果它工作了,你可以卸载cookie-session。

英文:

I think you need to clean up a bit your setting, since you're using CORS than you can first make some changes :

// .....
const app = express();

// with CORS you can do all your setting at the same place, so you don't need to set the header
const corsOptions = {
    origin: ["http://localhost:4000/api", "http://localhost:3000"],
    methods: "GET, POST, PUT, DELETE, OPTIONS, HEAD",
    credentials: true,  // for jwt/cookie !         
};
app.use(cors(corsOptions));

app.use(express.json());
app.use(express({ type: "application/vnd.api+json" }));
app.use(express.urlencoded({ extended: true }));
app.use(
  cookieSession({
        name: process.env.COOKIE_NAME,
        secret: process.env.COOKIE_SECRET, 
        maxAge: 24 * 60 * 60 * 1000,
        httpOnly: true,
        sameSite: false, //set this to "None" if you deploy to production on cross domaine.
        secure: false,  //set to true is required on production with https
   });

app.use("/uploads", express.static("uploads"));

const jobRoute = require("./routes/job.routes");
app.use("/api/", jobRoute);

module.exports = app;

Update the fetch part I clean up (I remove the header) and i just notice on your job.controller.js you put data property on your response json.. so you need to check again your database structure if it's still not working.

useEffect(() => { 
const fetchData = async () => {
    try {
        const response = await fetch("http:localhost:4000/api/jobs", {
           credentials: "include", //to be able to send with cookies...
        });
        if(response.ok) {
            const newData = await response.json();
            console.log(newData);
            setName(newData.data.jobs.name); // this part you need to check your data structure again...
        }
    } catch (error) {
        console.log(error)
    }
  }  
    fetchData();
}, []);

Optional note: this part is not part of your question, just in case if there is still issue with the cookie-session and jwtoken, you can change how the JWT is stored in the cookie: cookie-session purpose is to create a "session id" to authenticate the user by storing it at the client side (on the browser, with the cookie), i don't really see the point to use this if you're gonna use jwt token to authenticate anyway ? I let you see the step below if you re still stuck at this part:

First, you may need to install cookie-parser middleware, because if this method work for you, you will be able to uninstall cookie-session.

const cookieParser = require('cookie-parser')
/...
app.use(cookieParser());

on the auth.controllers.js

const loginAuth = async (req, res) => {
    try {
      const token = await authServices.login(req.body);
      // set the jwt token on the cookie
      res.cookie("jwt", token, {
        maxAge: 24 * 60 * 60 * 1000,
        httpOnly: true,
        sameSite: false, //set this to "None" if you deploy to production on cross domaine.
        secure: false,  //set to true is required on production with https
    }) 
        return res.status(200).json({
        //controller will return this message if the body sent was match
        message: "User logged in successfully!",
        });
    } catch (error) {
      //ratther it will return this erroe message
      return res.status(500).json({ message: error.message });
    }
  };

   //create a logout session for the user to logout by signing session to null
    const logoutAuth = async (req, res) => {
        res.clearCookie("jwt")
        return res.status(200).send({ message: "User logged out successfully!" });
    };

You also need to replace const token = req.session.token; in your activeAuth function, and in your auth.middleware.js at the auth middleware function by this:

 const token = req.cookies["jwt"]  //or
 const token = req.cookies.jwt

Finally if it work you can uninstall cookie-session.

huangapple
  • 本文由 发表于 2023年1月9日 03:25:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定