I got stocked on how to fech data from node to react using axios

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?

yes i have auth setup in my node and i everything is working perfect in postman

this is my auth code :

all my node looks like this:

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:

OK, look at the network call in the browser dev tools. See what is being sent, see how it differs from what you are sending in postman.

yes the network call are the same in both the browser and the postman “http://localhost:4000/api/jobs

If it is an endpoint behind auth, you have to be sending more than that. Do you have your server logging out? Is it seeing an incoming call?

my server looks like this:

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

});

And my app.js looks like this:

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

route.js

const router = require("express-promise-router")();

const jobController = require("../controllers/job.controller");

const auth = require("../middleware/auth.middleware");

router.get("/jobs", auth, jobController.getAllJobs);

I wasn’t asking to see your code. I was asking if your server is logging out what it is receiving. I’m trying to help you debug this.

Please take a look at the coodes i send to you, that is how i created the jobs database

yes here:

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

});

I’m not asking you to list your code. I’m asking you to log out what is happening in that endpoint and any middleware to figure out why it isn’t working. I’m not trying to fix your car for you, I’m trying to help you learn how to do it.

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