添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

please i need someone to help me with fetching data from node to react, these are the codes i have tried so far but were giving me errors:

useEffect(() => {
    const getJobs = async () => {
      try {
        const response = await axios.get("http://localhost:4000/api/jobs");
        console.log(response);
      } catch (err) {}
    getJobs();
  }, []);
const response = axios.get(`http://localhost:4000/api/jobs/`);
  try {
    console.log(response);
  } catch (error) {}

And here is the error mesage:

Promise {<pending>}
VM48 installHook.js:1861 Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "rejected"[[PromiseResult]]: AxiosError
xhr.js:247          GET http://localhost:4000/api/jobs/ 401 (Unauthorized)
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
Joblist @ Joblist.js:12
renderWithHooks @ react-dom.development.js:16305
mountIndeterminateComponent @ react-dom.development.js:20074
beginWork @ react-dom.development.js:21587
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
settle.js:19 Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
XMLHttpRequest.send (async)
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
Joblist @ Joblist.js:12
renderWithHooks @ react-dom.development.js:16305
mountIndeterminateComponent @ react-dom.development.js:20074
beginWork @ react-dom.development.js:21587
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
xhr.js:247          GET http://localhost:4000/api/jobs/ 401 (Unauthorized)
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
Joblist @ Joblist.js:12
renderWithHooks @ react-dom.development.js:16305
mountIndeterminateComponent @ react-dom.development.js:20145
beginWork @ react-dom.development.js:21587
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
settle.js:19 Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
              

First of all, you should put a logger in your catch block:

} catch (err) {
  console.error('getJobs error:', err)

But it’s probably going to be this, from the end of your error that you posted:

Uncaught (in promise) AxiosError {message: ‘Request failed with status code 401’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request: XMLHttpRequest, …}

So, the issue seems that you are not authorized to make that request - that’s usually what 401 means. Do you have some kind of auth set up? Does it need a cookie or a token or a key?

Have you played around with something like postman to see how to get this endpoint to work?

//importing functions and packages from their roots
const db = require("../config/database");
const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
dotenv.config();
//create auth(func) that accept the 3 params/argument which will ...
//prevent a sector to not been shown to a user that ...
//has have signed in or loged in
const auth = async (req, res, next) => {
  //getting back the user token where user id was saved and put into cookie
  const token = req.session.token;
  // If token is not present which means user hasn't yet signed in, return error
  if (!token) {
    return res.status(401).send({ error: "Please Authenticate" });
  try {
    //if user has signed in, then decode the token to verify the user all secrete sign in
              

please i really want you to help me, i don’t know if you still remember me? I am Anthony from lisbon portugal.
We use to communicate through email last time untill i have some issues but i,m back now.

I have an interview with my employer in a week time and i have to get this done before then :pray:

app.listen(port, () => { console.log(`Server is running on port http://localhost:${port}`); 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 userRoute = require("./routes/user.routes"); const authRoute = require("./routes/auth.routes"); const sectorRoute = require("./routes/sector.routes"); const profileRoute = require("./routes/profile.routes"); const categoryRoutes = require("./routes/category.routes"); const companyRoute = require("./routes/company.routes"); const jobRoute = require("./routes/job.routes"); const skillRoute = require("./routes/skill.routes"); const jobSkillRoute = require("./routes/job_skill.routes"); const userJobRoutes = require("./routes/user_job.routes"); const browseByRoute = require("./routes/browse_by.routes"); app.use("/api/", userRoute); app.use("/api/", authRoute); app.use("/api/", sectorRoute); app.use("/api/", profileRoute); app.use("/api/", categoryRoutes); app.use("/api/", companyRoute); app.use("/api/", jobRoute); app.use("/api/", skillRoute); app.use("/api/", jobSkillRoute); app.use("/api/", userJobRoutes), app.use("/api/", browseByRoute); module.exports = app;

i defined the routes in another file and import it into app.js, then used middleware to run it. For example this is what each database route looks like after fetching the data from the database which i did in another file. lOr let me show you all the process once a time here

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

service.js

const db = require("../config/database");
const notificationServices = require("./notification.services");
const { jobReuseQuery } = require("../job reuseable query/job.queries");
const getAllJobs = async () => {
  const { rows } = await db.query(
    SELECT
    jobs.* 
    FROM "jobs"
    LEFT JOIN companies ON companies.id = jobs.company_id 
    GROUP BY jobs.id
  return rows;

controller.js

const getAllJobs = async () => {
  const { rows } = await db.query(
    SELECT
    jobs.* 
    FROM "jobs"
    LEFT JOIN companies ON companies.id = jobs.company_id 
    GROUP BY jobs.id
  return rows;

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(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);
const router = require("express-promise-router")();
const jobController = require("../controllers/job.controller");
const auth = require("../middleware/auth.middleware");
router.get("/jobs", auth, jobController.getAllJobs);
app.listen(port, () => {
console.log(`Server is running on port http://localhost:${port}`);

That looks weird to me. I don’t do express much, But I would expect something like:

app.use("/api/user", userRoute);
app.use("/api/auth", authRoute);
// ...
              

yes i thought as much because i have tried it that way and it gives me more error and i know why. The userRoute is a router route that is coming from router.js files and it has the value of user already, it looks like this :

router.post("/users", userController.createUser);

i imported it from router.js file and then used middeware to plugin the route

That is why i sent you the codes to be able to see what i planned and how i used middleware because if there is an error inside the middleware or the server i will get it in postman.

This is what i have been search for a week now to solve