背景:
跟网友讨论起来,是不是所有的跨域处理都需要后端的支持。我的观点是,前端有能力自己解决好跨域的,不需要后端,然后列举了jsonp,原生js等。
网友说jsonp也是需要跟后端约定好回调函数,这个确实。
我又查找了一下资料,可以用nginx反向代理解决跨域的问题。为了避免被打脸,亲自跑了一下代码。
代码实践
前端
新建文件夹HTML,根目录下新建index.html,在页面调用后端接口http://127.0.0.1:8011/api
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="getData()">获取127.0.0.1:8011数据</button>
<script>
function getData() {
var httpRequest = new XMLHttpRequest()
httpRequest.open('GET', '/api', true)
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var json = httpRequest.responseText;
console.log(json)
}
}
}
</script>
</body>
</html>
后端
新建文件夹API,在根目录下新建index.js,安装使用express搭建起一个简单服务
1.安装node,安装express
npm install express -s
2.新建index.js编写接口
const express = require('express')
const app = express()
app.get('/api', function (req, res) {
res.send('api')
})
app.listen(8011, () => {
console.log('running at http://127.0.0.1:8011')
})
3.启动服务, http://127.0.0.1:8081/api接口调用成功
node index.js
nginx
1.下载所需要的nginx(nginx.org/en/download…),建议下载稳定版本。
2.把写好的前端代码放置在nginx服务器上
3.配置参数nginx.conf,
server {
listen 8084; # 前端项目访问端口
server_name 127.0.0.1; # 访问地址
location / {
root html; # 前端代码放置目录
index index.html index.htm;
}
location /api/ {
proxy_pass http://127.0.0.1:8011; # 访问api请求时,nginx代理请求到8011端口服务器
proxy_redirect default;
}
}
4.启动nginx
start nginx
测试结果
浏览器输入http://127.0.0.1:8084,访问到前端页面
点击按钮,正确返回接口数据