前言
为解决Vue前端与Node.js服务端端数据请求传输问题,由于服务端和前端端口不同,数据请求跨域,故使用Axios与Cors实现Ajax跨域通信。
Vue前端:"http://localhost:8080"
Node.js服务端:"http://localhost:3000"
服务端配置
- 安装Cors组件
npm install cors --save
- 服务器跨域设置
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/>"
});
- 测试
在服务端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>
-
测试成功