Error: "Access to fetch at 'https://***.com/api/v1/user/validuser' from origin 'http://localhost:3000' has been blocked by CORS policy"

huangapple go评论77阅读模式
英文:

Error: "Access to fetch at 'https://***.com/api/v1/user/validuser' from origin 'http://localhost:3000' has been blocked by CORS policy"

问题

It seems like you're experiencing issues with your project while trying to fetch the backend from render.com to your frontend. The error screenshot you provided suggests that there might be a CORS (Cross-Origin Resource Sharing) issue since you are trying to make requests from your frontend to a different domain.

To solve this problem and make your project work smoothly, you can follow these steps:

  1. Configure CORS on Your Backend:
    In your backend code (server.js), you are using the cors package. Make sure that you have configured it correctly to allow requests from your frontend domain. You can update the origin option in the cors middleware to match the domain of your frontend.

    Example:

    app.use(cors({ origin: "https://your-frontend-domain.com" }));
    
  2. Check Render.com Configuration:
    Ensure that your backend deployed on render.com is correctly configured to accept requests from your frontend domain. Render.com might also have its own CORS settings that you need to configure through their dashboard.

  3. Verify API URLs:
    Double-check that the URLs you are using in your frontend code to make API requests match the correct domain and paths of your backend on render.com.

    Example:

    fetch("https://your-backend-domain.onrender.com/api/v1/user/validuser", {
      // Your fetch request configuration here
    });
    
  4. Test Locally:
    Before deploying your frontend, you can test your project locally to ensure that the backend and frontend communicate correctly. Run your frontend and backend on your local machine and verify that there are no CORS issues.

  5. Error Handling:
    Implement proper error handling in your frontend code to capture and display any errors that might occur during API requests. This will help you diagnose issues more easily.

  6. Console Debugging:
    Use browser developer tools to check the network requests and console logs for any error messages. This can provide valuable information about what's going wrong.

By following these steps, you should be able to resolve the CORS-related issues and make your project work smoothly. If you encounter any specific error messages or issues during the process, feel free to ask for more assistance.

英文:

I uploaded my backend into render.com . I wanted to fetch the backend from there to my frontend but it is not working . Rather it is showing this error.
This is the screenshot of the error
server.js

const express = require("express");
const colors = require("colors");
const morgan = require("morgan");
const dotenv = require("dotenv");
const cors = require("cors"); // Import the cors package
const connectDB = require("./config/db");
const Products = require("./models/productSchema");
const DefaultData = require("./defaultdata.");
const cookieParser = require("cookie-parser");
dotenv.config();

connectDB();

const app = express();

app.use(express.json());
app.use(cors({ origin: "http://localhost:3000" })); // Set the origin to allow requests from localhost:3000
app.use(cookieParser());
app.use(morgan("dev"));

app.use("/api/v1/user", require("./routes/userRoutes"));
app.use("/api/v1/product", require("./routes/productRoutes"));
app.use("/api/v1/cart", require("./routes/cartRoutes"));

const port = process.env.PORT || 8080;

app.listen(port, () => {
  console.log(
    `Server is running in ${process.env.NODE_MODE} Mode on port ${process.env.PORT}`
      .bgCyan.white
  );
});

DefaultData();

userRoutes.js:

const express = require("express");
const {
  registrationController,
  loginController,
  logoutController,

  validationController,
} = require("../controller/Controller");

const authmiddleware = require("../middleware/Authmiddleware");

//router abject
const router = new express.Router();

//routes

//POST  || registration
router.post("/registration", registrationController);

//POST  || login
router.post("/login", loginController);

//GET || logout
router.get("/logout", authmiddleware, logoutController);

//GET || Get cart items
router.get("/validuser", authmiddleware, validationController);

module.exports = router;

Navbar.js:

import React, { useContext, useEffect, useState } from "react";
import "../../styles/Navbar.css";
import SearchIcon from "@mui/icons-material/Search";
import Badge from "@mui/material/Badge";
import ShoppingCartIcon from "@mui/icons-material/ShoppingCart";
import Avatar from "@mui/material/Avatar";
import { NavLink, useNavigate } from "react-router-dom";
import { Logincontext } from "../context/ContextProvider";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import Drawer from "@mui/material/Drawer";
import Leftheader from "./Leftheader";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import LogoutIcon from "@mui/icons-material/Logout";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useSelector } from "react-redux";
const Navbar = () => {
const { account, setAccount } = useContext(Logincontext);
// console.log(account);
const navigate = useNavigate();
//Menu Collect from material-ui
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
//serach bar
const [text, setText] = useState("");
// console.log(text);
const [listopne, setListopen] = useState(true);
const { products } = useSelector((state) => state.getproductsdata);
// get valid user
const getValiduserDetails = async () => {
const res = await fetch(
"https://amazon-application.onrender.com/api/v1/user/validuser",
{
method: "GET",
headers: {
Accept: "application/json",
"content-Type": "application/json",
},
credentials: "include",
}
);
const data = await res.json();
console.log(data);
if (res.status === 400) {
// console.log("User is not logged in");
} else {
// console.log("Valid user");
setAccount(data);
}
};
const [drawerOpne, setDrawerOpen] = useState(false);
// handle drawer
const handleDraweOpen = () => {
setDrawerOpen(true);
};
const handleDraweClose = () => {
setDrawerOpen(false);
};
//logout user
const logoutuser = async () => {
const res2 = await fetch(
"https://amazon-application.onrender.com/api/v1/user/logout",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "include",
}
);
const data2 = await res2.json();
// console.log(data2);
if (!res2.status === 201) {
const error = new Error(res2.error);
throw error;
} else {
setAccount(false);
// setOpen(false)
toast.success("Logout Successfull", {
position: "top-center",
});
navigate("/");
}
};
const getText = (iteams) => {
setText(iteams);
setListopen(false);
};
useEffect(() => {
getValiduserDetails();
}, []);
return (
<header>
<nav>
<div className="left">
<IconButton className="appbar" onClick={handleDraweOpen}>
<MenuIcon style={{ color: "#fff" }} />
</IconButton>
<Drawer open={drawerOpne} onClose={handleDraweClose}>
<Leftheader logClose={handleDraweClose} />
</Drawer>
<div className="navlogo">
<NavLink to="/">
<img src="./amazon_PNG25.png" alt="amazon_logo" />{" "}
</NavLink>
</div>
<div className="nav_searchbaar">
<input
type="text"
name=""
onChange={(e) => getText(e.target.value)}
placeholder="Search Your Procucts"
id=""
/>
<div className="search_icon">
<SearchIcon id="search" />
</div>
{/* Search Filter */}
{text && (
<List className="extrasearch" hidden={listopne}>
{products
.filter((product) =>
product.title.longTitle
.toLowerCase()
.includes(text.toLocaleLowerCase())
)
.map((product) => (
<ListItem>
<NavLink
to={`/getproductsone/${product.id}`}
onClick={() => setListopen(true)}
>
{product.title.longTitle}
</NavLink>
</ListItem>
))}
</List>
)}
</div>
</div>
<div className="right">
<div className="nav_btn">
<NavLink to="/login">Signin</NavLink>
</div>
<div className="cart_btn">
{account ? (
<NavLink to="/buynow">
<Badge badgeContent={account.carts.length} color="primary">
{/* <Badge badgeContent={4} color="primary"> */}
<ShoppingCartIcon id="icon" />
</Badge>
</NavLink>
) : (
<NavLink to="/login">
<Badge badgeContent={0} color="primary">
<ShoppingCartIcon id="icon" />
</Badge>
</NavLink>
)}
<p>Cart</p>
</div>
{account ? (
<Avatar
className="avtar2"
id="basic-button"
aria-controls={open ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
onClick={handleClick}
>
{account.fname[0].toUpperCase()}
</Avatar>
) : (
<Avatar
className="avtar"
id="basic-button"
aria-controls={open ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
onClick={handleClick}
></Avatar>
)}
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
"aria-labelledby": "basic-button",
}}
>
<MenuItem onClick={handleClose} style={{ margin: 10 }}>
My account
</MenuItem>
{account ? (
<MenuItem onClick={handleClose} style={{ margin: 10 }}>
<LogoutIcon
style={{ fontSize: 25, marginRight: 5 }}
onClick={logoutuser}
/>
Logout
</MenuItem>
) : (
""
)}
</Menu>
</div>
<ToastContainer />
</nav>
</header>
);
};
export default Navbar;

I want a relevant solution which can solve this problem so my project work smoothly

答案1

得分: 1

在你的跨域设置中:

app.use(cors({ origin: "http://localhost:3000" }));

你需要明确允许设置凭据:

app.use(cors({ origin: "http://localhost:3000", credentials: true }));

你可以在这里阅读有关跨域选项及其含义的信息:
https://expressjs.com/en/resources/middleware/cors.html

英文:

Here in your cors setup
app.use(cors({ origin: "http://localhost:3000" }));
You need to specifically allow credentials to be set
app.use(cors({ origin: "http://localhost:3000", credentials: true }));

You can read about the cors options and what they mean here:
https://expressjs.com/en/resources/middleware/cors.html

huangapple
  • 本文由 发表于 2023年5月22日 00:26:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定