app.use(cors())的作用是什么? [英] what does app.use(cors()) do?

查看:529
本文介绍了app.use(cors())的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们无法访问具有与我们域不同域的API.但是,我看到很多人在Express中安装 cors 模块以使用API​​,然后像这样使用它:

I know that we cannot have access to an API that has different domain there ours. However, I see many people installing the cors module in express to use APIs and then using it like so:

app.use(cors());

它实际上是做什么的?此功能如何在服务器上启用 cors ?

What does it actually do? How does this function enable cors on the server?

推荐答案

摘要

如您所说,它启用了 CORS (跨域资源共享).为了使您的服务器可以被其他来源(域)访问.

Abstract

As you said, it enables CORS (cross-origin resource sharing). In order for your server to be accessible by other origins (domains).

调用 use(cors())将使 express服务器响应预检请求.

Calling use(cors()) will enable the express server to respond to preflight requests.

预检请求基本上是在发送实际请求之前向服务器发送的 OPTION 请求,以询问服务器接受哪个起源和哪个请求选项.

A preflight request is basically an OPTION request sent to the server before the actual request is sent, in order to ask which origin and which request options the server accepts.

因此 CORS 基本上是服务器发送到浏览器的一组标头.在没有其他信息的情况下调用 cors()将设置以下默认值:

So CORS are basically a set of headers sent by the server to the browser. calling cors() with no additional information will set the following defaults:

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

这些被翻译为以下标头:

these are translated into these headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Status Code: 204

这样做基本上是使您的服务器对任何通过浏览器向服务器请求资源的域都可访问.

What is this doing is basically making your server accessible to any domain that requests a resource from your server via a browser.

您可以在此处检查所有明确的 cors 配置: https://github.com/expressjs/cors

you can check all the express cors configurations here: https://github.com/expressjs/cors

您还可以在此处阅读有关浏览器 cors 的更多信息: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

you can also read more about browser cors here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

这篇关于app.use(cors())的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆