Access to XMLHttpRequest at 'http://localhost:5000/api/products' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Contr

Viewed 687

I'm trying to fetch data created on db ,through postman using axios,i keep getting no access control cors error. I have added the "Moesif Origin & CORS Changer" plugin to my chrome still no solution. I required cors on the server i get the same issue. I dont know what i'm doing wrong.I have read and tried several solutions given here.

My Client side code(React.JS)

import styled from "styled-components";
import { popularProducts } from "../data";
import Product from "./Product";
import axios from "axios";
import { useState, useEffect } from "react";

const Container = styled.div`
padding: 20px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
`;

const Products = ({ cat, filter, sort }) => {
const [products, setProducts] = useState([]);
const [filteredProducts, setFilteredProducts] = useState([]);

useEffect(() => {
const getProducts = async () => {
  try {
    const res = axios.get("http://localhost:5000/api/products");
    console.log(res);
  } catch (err) {}
 };
 getProducts();
 }, [cat]);

My Backend API (Express)

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");

const  cors = require("cors");


dotenv.config();

 mongoose
   .connect(process.env.MONGO_URL)
   .then(() => console.log("DB connection successful"))
   .catch((error) => {
    console.log(error);
  });

//middleware
app.use(express.json());

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/products", productRoute);
app.use("/api/carts", cartRoute);
app.use("/api/orders", orderRoute);
app.use(cors());

app.listen(process.env.PORT || 5000, () => {
console.log("Backend server is running");
});
3 Answers

The problem is that you include the cors middleware at the bottom of your middleware stack, so it would only ever be reached if none of the routes match, i.e. your 404 errors would have CORS headers but nothing else would:

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/products", productRoute); // This route handles the request
                                        // and ENDS the request processing
app.use("/api/carts", cartRoute);
app.use("/api/orders", orderRoute);
app.use(cors());                        // This is never reached!

You need the CORS headers always, so you have to put the middleware at the top of the stack:

app.use(cors());                        // This is executed first, adds the
                                        // headers and continues processing
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/products", productRoute); // This route handles the request
app.use("/api/carts", cartRoute);
app.use("/api/orders", orderRoute);

First, check the cors version, if it doesn't work, try to use a proxy.

you can use proxy as follow,

in your front-end, pacakge.json just add this line of code.

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

And in your Axios.get remove thie http://localhost:5000 and

   axios.get("http://localhost:5000/api/products");

Instead, do it like this

    const res = axios.get("/api/products");

And if both doesn't work, then try to install and import body-parser on your server-side.

installtion:
npm i body-parser

import:
const bodyParser = require('body-parser')

Try creating a file called: setupProxy.js within your src folder in client. Install http-setup-proxy

Add this to setupProxy.js:

const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:5000',
            changeOrigin: true,
        }),
    )
}

Finally, restart your application.

Related