1.需求
使用vue-cli2 搭建的框架
使用nodejs的express搭建的后台
利用nginx使得跨域成功
2.Nginx 下载安装
到官网下载Nginx,解压,
下载完成后,解压缩 就好了很简单
nginx 安装好之后可以进行下一步了
3. 正式开始
首先搭建一个vue-cli2脚手架,搭建脚手架的原因是:
(发送请求需要以服务器方式打开网页,不能以文件形式)
利用原生ajax写的请求,之后运行
前端代码块:
<template>
<div id="app">
<button @click="getKo">向服务器发送请求Ko(跨域成功)</button>
<button @click="getBo">向服务器发送请求Bo(跨域失败)</button>
<h1 id='test-response-text'>显示服务器响应内容</h1>
</div>
</template>
<script>
export default {
data () {},
methods: {
getKb (demo, url) {
let request = new XMLHttpRequest()
let textDemo = document.getElementById(demo)
request.onreadystatechange = () => { // 状态发生变化时,函数被回调
if (request.readyState === 4 && request.status === 200) { // 成功完成
// 成功,通过responseText拿到响应的文本:
let text = request.responseText
textDemo.innerHTML = text
}
}
// 发送请求:
request.open('GET', url, true)
request.send()
},
getKo () {
this.getKb('test-response-text', 'http://localhost:3000/ko')
},
getBo () {
this.getKb('test-response-text', 'http://localhost:3000/Bo')
}
}
}
</script>
利用node的express框架开启服务,并根据url返回json格式的数据 , 我这里随便写了
后端代码块:
const express = require("express")
const app = express()
app.listen(3000,(res)=>{
console.log("成功")
})
app.get("/",(req,res)=>{ // 测试
res.send("测试成功")
})
app.get("/ko",(req,res)=>{ //访问地址
res.send("ko----访问成功")
})
app.get("/bo",(req,res)=>{ // 失败
res.send("0")
})
之后运行 node app.js (文件名称)
运行成功之后可以执行在本地打开浏览器访问 localhost:3000
此时我们可以进入页面进行访问
显示跨域不允许访问
4.nginx 配置
解压缩之后找到 conf / nginx.conf
对 nginx.conf 进行修改
我们主要修改是server下面的代码
server
{
listen 3002;
server_name localhost;
location / {
# 指定允许跨域的方法,*代表所有
add_header Access-Control-Allow-Methods *;
# 带cookie请求需要加上这个字段,并设置为true
add_header Access-Control-Allow-Credentials true;
proxy_pass http://localhost:3000;
}
location /bo {
proxy_pass http://localhost:3000/bo;
}
location /ko {
# 指定允许跨域的方法,*代表所有
add_header Access-Control-Allow-Methods *;
# 带cookie请求需要加上这个字段,并设置为true
add_header Access-Control-Allow-Credentials true;
proxy_pass http://localhost:3000/ko;
}
}
上面代码的意思是将localhost:3002转发为location:3000;也就是说现在访问后端localhost:3002实际上是访问location:3000,而访问localhost:3002/ko则是访问localhost:3000/ko,并以ko开头的url
我们开启nginx服务
在nginx目录下使用 **start nginx ** 即可开启服务
每次修改配置都需要执行 nginx -s reload 命令才能生效
或者可以直接双击nginx.exe
成功启动后,可以访问localhost:3002访问
5.改写请求url
这个必须要改写,不然还是等于访问3000的端口号
这个改的就是我们直接前端代码块的请求,改写成我们nginx启动的端口,之后就可以访问了
getKo () {
this.getKb('test-response-text', 'http://localhost:3002/ko')
},
getBo () {
this.getKb('test-response-text', 'http://localhost:3002/Bo')
}
如果觉得我的文章对你有用,请点赞鼓励
附件一个git地址可以查看 github.com/zhaolongyu/…