首先創建vue項目:
在helloWord.vue組件中改造,如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<button @click="handleClick">請求後端接口</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: '測試nginx部署項目使用'
}
},
methods:{
handleClick () {
//請求後端接口
this.$api.get('/yu/test',{},response => {
alert('調用後端返回的數據是什麼:' + response.data)
});
console.log("hello");
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
創建axios請求工具類:
import axios from 'axios'
let http = axios.create({
baseURL: 'http://localhost:8088/',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: [function (data) {
let newData = '';
for (let k in data) {
if (data.hasOwnProperty(k) === true) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
}
}
return newData;
}]
});
function apiAxios(method, url, params, response) {
http({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
}).then(function (res) {
response(res);
}).catch(function (err) {
response(err);
})
}
/*
* 封裝get,post,put,delete方法
* */
export default {
get: function (url, params, response) {
return apiAxios('GET', url, params, response)
},
post: function (url, params, response) {
return apiAxios('POST', url, params, response)
},
put: function (url, params, response) {
return apiAxios('PUT', url, params, response)
},
delete: function (url, params, response) {
return apiAxios('DELETE', url, params, response)
}
}
需要用到axios,安裝axios插件:
cnpm install axios --save
將這個工具類設爲全局組件可用,需要在main.js中定義,如下:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入自定義的js,以便在其他js/組件中全局使用,使用方式爲 this.$api開頭
import Api from './util/request.js';
Vue.prototype.$api = Api;
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
啓動項目,訪問如下,端口默認8080
創建sqpring boot項目,端口9090
就一個controller類:
package com.wm.test.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/yu")
public class TestController {
@GetMapping("/test")
public String test(){
return String.format("hello,world!");
}
}
啓動項目,訪問接口:
http://localhost:9090/yu/test 如下:
下面開始配置nginx:
打開nginx.conf文件
首先,監聽端口8088,其次,設置解決跨域處理:
listen 8088;
server_name localhost;
location / {
root demo\dist;
index index.html index.htm;
}
# 反向代理springboot接口服務,請求/yu的接口全部反向代理到spring boot項目中去,解決跨域問題
location /yu {
proxy_pass http://localhost:9090/yu; # 後端接口 IP:port
}
說明下,訪問首頁爲vue中的index頁面,root目錄爲demo/dist;
完整的配置如下:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 8088;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root demo\dist;
index index.html index.htm;
}
# 反向代理springboot接口服務,請求/yu的接口全部反向代理到spring boot項目中去,解決跨域問題
location /yu {
proxy_pass http://localhost:9090/yu; # 後端接口 IP:port
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
說明:當訪問/yu開頭的路徑時候,nginx會轉發到http://localhost:9090/yu 開頭的路徑,也就解決了跨域問題
將前端項目打包:
cnpm run build
打包後再nginx中新建目錄demo:
將打包後的文件dist全部放在demo文件夾中:
弄好之後,啓動nginx,和後端項目,訪問路徑:
http://localhost:8088
可以看到nginx監聽到了8088端口並將我們的請求抓到index頁面:
點擊請求後端接口按鈕:
可以看到請求成功了,並且只發送一次請求,並沒有發送OPTIONS請求,原因是瀏覽器發送的請求到nginx,nginx幫我們轉發請求,不是瀏覽器直接發送請求到後端的,不需要校驗跨域請求,而且也沒有進行跨域請求。