空白cors策略阻止我在expressjs中的请求

问题描述 投票:0回答:1

我向服务器发送请求时遇到此问题:

Access to XMLHttpRequest at 'http://localhost:5000/api/distance' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 

我的CORS策略和ExpressJS服务器外观:

let PORT = process.env.PORT,
  MONGO_DB_URL = process.env.MONGO_DB_URL
const app = express();

if (process.env.MODE === "DEV") {
  PORT = 5000
  MONGO_DB_URL = `mongodb://localhost:27017/tt111`
  app.use(cors({origin: 'http://localhost:3000'}))
  console.log("asd")
} else {
  app.use(cors({ credentials: true, origin: 'http://localhost:5000' }));
}

app.use(express.static(path.join(__dirname, '../client/build')));
mongodbConnection(MONGO_DB_URL);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use("/api/distance", roadRoutes());
app.use("/api/webStatsRoutes", webStatsRoutes());
app.use("/api/contact", contactRoutes())
app.get('*', (req, res) => {
  console.log(path.join(__dirname, '../client/build/index.html'))
  res.sendFile(path.join(__dirname, '../client/build/index.html'));
});

服务器启动时,在控制台中显示:“ asd”,因此我设置了开发人员模式(请查看if语句)。

我的请求来自在本地主机上运行的React应用:3000。我的axios请求:

 axios.post(`${API_URL}/api/distance`, data).then((response) => {
                console.log(response)
                this.setState({
                    ...this.state,
                    isLoading: false,
                    resultSearchedData: response.data.companies || [],
                })
                this.props.getAllCompanies(response.data.companies)

            }, (err) => {
                console.log("Axios error: " + err)
            })

我正在尝试使用完全空白的策略,例如:

app.use(cors())

并带有凭据:

app.use(cors({ credentials: true,origin: 'http://localhost:3000'}))
node.js reactjs express http cors
1个回答
0
投票

[请检查您是否已将localhost与127.0.0.1交换,因为这通常是导致开发中此错误的原因,因为它是您的cors策略中未指定的其他地址。

此行中另一个可能的问题:

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

由于您是从:5000应用程序运行,因此您应将客户端代码切换为5000,因此您甚至设置了PORT变量,因此这可能是一个错字。

© www.soinside.com 2019 - 2024. All rights reserved.