📜  如何在 Express 中允许 CORS?

📅  最后修改于: 2022-05-13 01:56:28.899000             🧑  作者: Mango

如何在 Express 中允许 CORS?

CORS一词代表“跨域资源共享”。跨域资源共享是一种由浏览器实现的基于 HTTP 标头的机制,它允许服务器或 API(应用程序编程接口)指示除其来源之外的任何来源(在协议、主机名或端口方面不同)未知来源获得访问和加载资源的权限。

项目设置和模块安装:

第 1 步:创建一个 Node.js 应用程序并使用以下命令将其命名为gfg-cors

mkdir geeksforgeeks && cd geeksforgeeks
npm init 

第 2 步:使用以下命令安装依赖模块。

npm i express cors

第三步:在根目录下创建client目录和server.js文件。然后在客户端目录下创建index.htmlscript.js

项目目录:它看起来像这样。

示例:这是 index.html 和 script.js 文件中的代码。

index.html


  

    
    
    
    Sample webpage
    

  


  


Javascript
fetch('http://localhost:5000/secret')
    .then((res) => res.json())
    .then((data) => console.log(data))


index.js
// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for any unknow origin(https://xyz.example.com)
app.use(cors());
  
// sample api routes for testing
app.get('/', (req, res) => {
    res.json("welcome to our server")
});
  
app.get('/secret', (req, res) => {
    const secret = Math.floor(Math.random() * 100)
    res.json({ secret })
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
    console.log(`Server running on port ${port}.`)
})


index.js
// index.js file
  
// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for some specific origins only.
let corsOptions = {
   origin : ['http://localhost:5500'],
}
  
app.use(cors(corsOptions))
  
// sample api routes for testing
app.get('/',(req, res) => {
   res.json("welcome to our server")
});
  
app.get('/secret', cors(corsOptions) , (req, res) => {
   const secret =  Math.floor(Math.random()*100)
   res.json({secret})
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
   console.log(`Server running on port ${port}.`)
});


Javascript

fetch('http://localhost:5000/secret')
    .then((res) => res.json())
    .then((data) => console.log(data))

我们已经完成了基本的代码文件,现在转到主题,看看如何在 Express 中允许 CORS

为所有路由启用 CORS:如果要允许选定的源访问您的站点,则需要配置 cors,如下所示。

句法:

const cors = require(cors)
app.use(cors())

示例:为服务器的所有路由启用 CORS,新的 index.js 将喜欢:

index.js

// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for any unknow origin(https://xyz.example.com)
app.use(cors());
  
// sample api routes for testing
app.get('/', (req, res) => {
    res.json("welcome to our server")
});
  
app.get('/secret', (req, res) => {
    const secret = Math.floor(Math.random() * 100)
    res.json({ secret })
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
    console.log(`Server running on port ${port}.`)
})

运行应用程序的步骤:使用以下命令运行 server.js。

node server.js

输出:

指定路由的 CORS:

但是可能存在这样的情况,即只允许一定数量的未知来源从我们的服务器访问资源,并且出于机密性,我们需要保护我们的服务器免受潜在的入侵者(任何不遵循同源策略的 URL)的侵害。在这里,我们将为一定数量的来源启用 CORS 请求,如下所示:});

句法:

let corsOptions = {
   origin : ['http://localhost:5500'],
}

index.js

// index.js file
  
// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for some specific origins only.
let corsOptions = {
   origin : ['http://localhost:5500'],
}
  
app.use(cors(corsOptions))
  
// sample api routes for testing
app.get('/',(req, res) => {
   res.json("welcome to our server")
});
  
app.get('/secret', cors(corsOptions) , (req, res) => {
   const secret =  Math.floor(Math.random()*100)
   res.json({secret})
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
   console.log(`Server running on port ${port}.`)
});

运行应用程序的步骤:使用以下命令运行 server.js。

node server.js

输出: