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

Posted

技术标签:

【中文标题】空白 cors 政策阻止我在 expressjs 中的请求【英文标题】:Blank cors policy block my request in expressjs 【发布时间】: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'))

【问题讨论】:

过去,它工作正常。 【参考方案1】:

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

另一个可能的问题在这一行:

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

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

【讨论】:

客户端运行在 localhost:3000 而不是 localhost:5000 @newmaster 好的!那么问题出在 127.0.0.1 部分? 不,我将来源设置为 localhost:3000 并且凭据为真

以上是关于空白 cors 政策阻止我在 expressjs 中的请求的主要内容,如果未能解决你的问题,请参考以下文章

CORS 开发政策阻止的所有请求

被 CORS 政策阻止 - React - MangoPay

ExpressJs 应用程序中的 cors-js 阻止了应该通过的请求

为啥我收到 Cors 错误:...已被 CORS 政策阻止

被 CORS 政策阻止并没有解决! Laravel + Vuejs

为啥我的 formdata POST 没有被 Cors 政策阻止?