如何在 Express Node.js 项目中处理 CORS 错误

如何在 Express Node.js 项目中处理 CORS 错误

CORS,也称为跨域资源共享,如果你希望在不同URL上的客户端和服务器之间进行请求,就需要启用它。

让我们假设客户端位于 http://localhost:5500 ,服务器位于 http://localhost:5000 。现在,如果你尝试从客户端向服务器发起请求,你将收到一个错误,提示被 CORS 策略阻止。

如何在 Express Node.js 项目中处理 CORS 错误

如何启用CORS?

我们将使用cors这个node.js包在express Node.js项目中启用CORS。

项目设置和模块安装:

  • 步骤1: 创建一个Node.js应用并将其命名为gfg-cors,使用以下命令。
mkdir gfg-cors && cd gfg-cors
npm init 
JavaScript
  • 步骤2: 使用以下命令安装依赖模块。
npm i express cors
JavaScript
  • 步骤3: 在根目录下创建client目录和server.js文件。然后在client目录中创建index.htmlscript.js

项目目录结构:

它会像这样。

如何在 Express Node.js 项目中处理 CORS 错误

示例: 将以下代码写入 index.html, script.js , 和 server.js 文件中。

index.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
    <title>gfg-cors</title> 
    <script src="script.js"></script>  
</head> 
<body>   
</body> 
</html>
JavaScript

script.js

fetch('http://localhost:5000/gfg-articles') 
.then((res) => res.json()) 
.then((gfg_articles) => console.log(gfg_articles)); 
JavaScript

server.js

// Requiring module 
const express = require('express'); 
const cors = require('cors'); 
  
// Creating express app object 
const app = express(); 
  
// CORS is enabled for all origins 
app.use(cors()); 
  
// Example api  
app.get('/gfg-articles',  
    (req, res) => res.json('gfg-articles')); 
  
// Port Number 
const port = 5000; 
  
// Server setup 
app.listen(port, () => `Server running on port ${port}`);
JavaScript

注意: 如果您希望允许选择的源访问您的网站,那么您需要按照下面的示例配置cors。

server.js

// Requiring module 
const express = require('express'); 
const cors = require('cors'); 
  
// Creating express app object 
const app = express(); 
  
// CORS is enabled for the selected origins 
let corsOptions = { 
    origin: [ 'http://localhost:5500', 'http://localhost:3000' ] 
}; 
  
// Using cors as a middleware 
app.get('/gfg-articles',cors(corsOptions), 
    (req,res) => res.json('gfg-articles')) 
  
// Port number 
const port = 5000; 
  
// Server setup 
app.listen(port, () => `Server running on port ${port}`);
JavaScript

如果您只希望允许特定的来源访问您的网站,则 corsOptions(跨域选项) 如下所示:

let corsOptions = {
    origin: 'http://localhost:5500'
};
JavaScript

运行应用程序的步骤:

使用以下命令运行server.js。

node server.js
JavaScript

输出: 打开 index.html 然后在控制台中检查以下输出。

如何在 Express Node.js 项目中处理 CORS 错误

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册