前言
為解決Vue前端與Node.js服務(wù)端端數(shù)據(jù)請(qǐng)求傳輸問題,由于服務(wù)端和前端端口不同,數(shù)據(jù)請(qǐng)求跨域,故使用Axios與Cors實(shí)現(xiàn)Ajax跨域通信。
Vue前端:"http://localhost:8080"
Node.js服務(wù)端:"http://localhost:3000"
服務(wù)端配置
- 安裝Cors組件
npm install cors --save
- 服務(wù)器跨域設(shè)置
main.js
var express = require("express");
var cors = require("cors");
var app = express();
app.use(
cors({
origin: ["http://localhost:8080"],
methods: ["GET", "POST"],
alloweHeaders: ["Content-Type", "Authorization"]
})
);
app.get("/getNewsList", function(req, res, next) {
res.send("get /getNewsList");
console.log("get /getNewsList");
});
app.get("/vueTest", function(req, res, next) {
res.send("get /vueTest");
console.log("get /vueTest");
});
app.listen(3000);
console.log("[Listening on port 3000...");
也可添加以下命令,允許任意跨域訪問
app.all("*", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", " 3.2.1");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
前端配置
- 安裝axios組件
npm install axios --save
- 安裝cors及vue-cors組件
npm install cors --save
npm install vue-cors --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";
import axios from "axios";
import VueAxios from 'vue-axios'
import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";
Vue.use(VueAxios,axios);
Vue.use(Vuetify);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: "#app",
router,
components: { App },
template: "<App/>"
});
- 測(cè)試
在服務(wù)端app.js中添加
app.get("/getNewsList", function(req, res, next) {
res.send("get /getNewsList");
console.log("get /getNewsList");
});
app.get("/vueTest", function(req, res, next) {
res.send("get /vueTest");
console.log("get /vueTest");
});
在任一components中加入
<script>
export default {
name:'vcardNews',
data(){
return{
clists:[]
}
},
methods:{
/*
https://www.npmjs.com/package/vue-axios
*/
getNewsList(){
this.axios.get('http://localhost:3000/getNewsList').then((response) => {
alert(response.data);
this.clists = response.data;
})
}
},
mounted(){
this.getNewsList()
}
}
</script>
-
測(cè)試成功

