马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
目次
办理跨域请求问题的方法
1. 服务器端设置响应头
2. JSONP(JSON with Padding)
3. 代理服务器
场景示例
前端代码(使用 Fetch API)
后端代码(使用 Node.js + Express 并设置 CORS 响应头)
跨域资源共享(CORS,Cross-Origin Resource Sharing)是一种当代欣赏器为了安全而实验的同源策略所引发的问题。同源策略要求欣赏器在访问不同源(协议、域名、端口三者任意一个不同即为不同源)的资源时进行限定。以下具体介绍办理跨域请求问题(CORS)的方法。
办理跨域请求问题的方法
1. 服务器端设置响应头
这是办理 CORS 问题最常见和推荐的方法,通过在服务器端设置响应头来允许跨域请求。
原理:服务器通过设置特定的响应头,告诉欣赏器哪些源可以访问该资源,以及允许的请求方法、请求头和是否允许携带凭据等信息。
示例代码(以 Node.js + Express 为例):
- const express = require('express');
- const app = express();
- // 允许所有源的跨域请求
- app.use((req, res, next) => {
- res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有源访问
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的请求方法
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的请求头
- next();
- });
- // 处理 GET 请求
- app.get('/api/data', (req, res) => {
- res.json({ message: 'This is some data from the server.' });
- });
- const port = 3000;
- app.listen(port, () => {
- console.log(`Server is running on port ${port}`);
- });
复制代码 解释:
- Access-Control-Allow-Origin:指定允许访问该资源的源。* 表示允许全部源访问,但在生产环境中,为了安全起见,建议指定具体的源。
- Access-Control-Allow-Methods:指定允许的请求方法。
- Access-Control-Allow-Headers:指定允许的请求头。
2. JSONP(JSON with Padding)
JSONP 是一种古老的跨域数据交互技能,它使用了 <script> 标签的 src 属性不受同源策略限定的特点。
原理:服务器返回的数据被包裹在一个回调函数中,前端页面通过动态创建 <script> 标签来请求该数据,当请求完成后,会执行回调函数并将数据传递给它。
示例代码:
前端代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>JSONP Example</title>
- </head>
- <body>
- <script>
- function handleData(data) {
- console.log(data);
- }
- const script = document.createElement('script');
- script.src = 'http://example.com/api/data?callback=handleData';
- document.body.appendChild(script);
- </script>
- </body>
- </html>
复制代码 服务器端代码(以 Node.js 为例):
- const http = require('http');
- const server = http.createServer((req, res) => {
- const url = new URL(req.url, `http://${req.headers.host}`);
- const callback = url.searchParams.get('callback');
- const data = { message: 'This is some data from the server.' };
- const jsonp = `${callback}(${JSON.stringify(data)})`;
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(jsonp);
- });
- const port = 3000;
- server.listen(port, () => {
- console.log(`Server is running on port ${port}`);
- });
复制代码 范围性:JSONP 只支持 GET 请求,并且安全性较低,容易受到 XSS 攻击。
3. 代理服务器
在开辟环境中,可以使用代理服务器来办理跨域问题。代理服务器位于客户端和目标服务器之间,客户端向代理服务器发送请求,代理服务器再将请求转发到目标服务器,并将响应返回给客户端。
示例代码(以 Vue CLI 为例):
在 vue.config.js 中设置代理:
- module.exports = {
- devServer: {
- proxy: {
- '/api': {
- target: 'http://example.com', // 目标服务器地址
- changeOrigin: true,
- pathRewrite: {
- '^/api': ''
- }
- }
- }
- }
- };
复制代码 解释:
- target:目标服务器的地点。
- changeOrigin:是否改变请求的源。
- pathRewrite:对请求路径进行重写。
场景示例
假设你有一个前端项目运行在 http://localhost:8080,后端 API 服务运行在 http://localhost:3000,你想从前端项目中请求后端 API 的数据。
前端代码(使用 Fetch API)
- fetch('http://localhost:3000/api/data')
- .then(response => response.json())
- .then(data => console.log(data))
- .catch(error => console.error('Error:', error));
复制代码 后端代码(使用 Node.js + Express 并设置 CORS 响应头)
- const express = require('express');
- const app = express();
- app.use((req, res, next) => {
- res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
- next();
- });
- app.get('/api/data', (req, res) => {
- res.json({ message: 'This is some data from the server.' });
- });
- const port = 3000;
- app.listen(port, () => {
- console.log(`Server is running on port ${port}`);
- });
复制代码 通过以上设置,前端项目就可以正常请求后端 API 的数据,办理了跨域问题。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |