1

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.

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for replying. But I'm going to accept the other answer because it showed me how to set up cors.
0

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

  }, [])

  ...
}

4 Comments

But can you provide why my code doesn't work and what cors is?
Also hello world is getting logged two times.
@EthanLal You will have to use useEffect hook in order to make any side effect. Meaning, any CURD requests should go in useEffect hook, that way you will not have re rendering effects.
I'm going to edit my answer to reflect the useEffect hook usage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.