【发布时间】:2020-04-18 18:03:49
【问题描述】:
我在向服务器发送请求时遇到了这个问题:
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 语句)。
我的请求来自在 localhost:3000 上运行的 react 应用程序。 我的 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