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

时间:2019-12-29 21:01:52

标签: node.js reactjs express http cors

在向服务器发送请求时,我遇到了这个问题:

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'}))

1 个答案:

答案 0 :(得分:0)

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

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

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

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