Reputation:
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...
Any help would be appreciated.
Upvotes: 1
Views: 130
Reputation: 4333
Install cors
middleware in your backend server.
npm install cors
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