user14339485
user14339485

Reputation:

How to resolve get request with axios in React?

I'm new to Axios, and I was trying to fetch data from an endpoint to use in React...

import axios from "axios";

const api = axios.create({ baseURL: "http://localhost:5000/" });

export default function App() {
  api.get("/products").then(res => console.log(res.data));
  ...
}

Here is my endpoint code...

const express = require("express");
const app = express();

require("dotenv").config();

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

const port = process.env.PORT;
app.listen(port, () => console.log(`Listening on port ${port}...`));

But instead of the Hello world! getting logged I am getting this error...

null

Any help would be appreciated.

Upvotes: 1

Views: 130

Answers (2)

krsna
krsna

Reputation: 4333

Install cors middleware in your backend server.

  1. npm install cors
  2. Enable all CORS requests
const express = require("express");
var cors = require('cors')
const app = express();

app.use(cors())

You can look for more information here. There are ways to configure your CORS as well.

To your another question, CRUD operations should be used in useEffect hook.

import React, { useEffect } from 'react';

export default function App() {

  useEffect(() => {

    api.get("/products").then(res => console.log(res.data));

  }, [])

  ...
}

Upvotes: 0

Daphaz
Daphaz

Reputation: 506

Hi look for this lib Cors for express and you can use proxy in react project in your package.json instead of axios.create() like

"proxy": "http://localhost:5000"

Upvotes: 1

Related Questions