简体   繁体   English

CORS 政策已阻止从源“http://localhost:3000”访问“http://localhost:5000/api/products”处的 XMLHttpRequest:否“访问控制”

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

I'm trying to fetch data created on db,through postman using axios,i keep getting no access control cors error.我正在尝试使用 axios 通过 postman 获取在 db 上创建的数据,我一直没有访问控制 cors 错误。 I have added the "Moesif Origin & CORS Changer" plugin to my chrome still no solution.我已将“Moesif Origin & CORS Changer”插件添加到我的 chrome 中,但仍然没有解决方案。 I required cors on the server i get the same issue.我在服务器上需要 cors 我遇到了同样的问题。 I dont know what i'm doing wrong.I have read and tried several solutions given here.我不知道我做错了什么。我已经阅读并尝试了这里给出的几种解决方案。

My Client side code(React.JS)我的客户端代码(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)我的后端 API(快递)

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

First, check the cors version , if it doesn't work, try to use a proxy .首先,检查 cors 版本,如果它不起作用,请尝试使用代理

you can use proxy as follow,您可以使用代理如下,

in your front-end, pacakge.json just add this line of code.在您的前端, pacakge.json只需添加这行代码。

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

And in your Axios.get remove thie http://localhost:5000 and在你的 Axios.get 中删除 http://localhost:5000 和

   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.如果两者都不起作用,请尝试在您的服务器端安装并导入 body-parser。

installtion:
npm i body-parser

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

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, ie your 404 errors would have CORS headers but nothing else would:问题是您在中间件堆栈的底部包含了cors中间件,因此只有在没有任何路由匹配时才会到达它,即您的 404 错误将具有 CORS 标头,但没有其他任何内容:

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:始终需要 CORS 标头,因此您必须将中间件放在堆栈顶部

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

Try creating a file called: setupProxy.js within your src folder in client.尝试在客户端的 src 文件夹中创建一个名为 setupProxy.js 的文件。 Install http-setup-proxy安装http-setup-proxy

Add this to setupProxy.js:将此添加到 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.最后,重新启动您的应用程序。

i had the same issuse but i was able to fix it with following code in my server.js file where the origin:"https://127.0.0.1:5173" is my frontend's url that will be requesting data from the backend我有同样的问题,但我能够在我的 server.js 文件中使用以下代码修复它,其中来源:“https://127.0.0.1:5173”是我前端的 url 将从后端请求数据

const cors = require("cors")
app.options("*", cors())

const corsOptions = {
  origin:"http://127.0.0.1:5173"
}

app.use(cors(corsOptions))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 策略已阻止从源“http://localhost:62521”访问“localhost:3000/users”处的 XMLHttpRequest - Access to XMLHttpRequest at 'localhost:3000/users' from origin 'http://localhost:62521' has been blocked by CORS policy 由于 CORS 政策,从源 http://localhost:3000 访问 xmlhttprequest 已被阻止 - access to xmlhttprequest from origin http://localhost:3000 has been blocked due to CORS policy 使用 reactjs 和节点网络服务器的 CORS 策略已阻止访问从源“http://localhost:5000/login”获取“http://localhost:3000” - Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy using reactjs and node webserver Google Chrome Calling Express API — CORS 策略已阻止访问从源“http://localhost:3000”获取 - Google Chrome Calling Express API — Access to fetch at from origin 'http://localhost:3000' has been blocked by CORS policy CORS 策略已阻止从来源“localhost:3000”访问位于“...”的 XMLHttpRequest - Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy CORS 策略已阻止在 localhost:3000 访问 XMLHttpRequest - Access to XMLHttpRequest at localhost:3000 from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header 从源“http://localhost:3000”访问“https://sua-ap-web-1.agora.io/api/v1?action=stringuid”的 XMLHttpRequest 已被 CORS 策略阻止 - Access to XMLHttpRequest at 'https://sua-ap-web-1.agora.io/api/v1?action=stringuid' from origin 'http://localhost:3000' has been blocked by CORS polic 如何修复“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 - How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' 已阻止从源“ null”访问Twitter_OAuth_Url(从“ http:// localhost:3000 / api / twitter-login”重定向到)的XMLHttpRequest - Access to XMLHttpRequest at Twitter_OAuth_Url ( redirected from 'http://localhost:3000/api/twitter-login') from origin 'null' has been blocked 来自源“http://localhost:8080”的 AWS API GATEWAY 已被 CORS 策略阻止 - AWS API GATEWAY from origin 'http://localhost:8080' has been blocked by CORS policy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM