十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
小編給大家分享一下VUE+node如何實現(xiàn)前后端分離,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)建站始終堅持【策劃先行,效果至上】的經(jīng)營理念,通過多達(dá)10多年累計超上千家客戶的網(wǎng)站建設(shè)總結(jié)了一套系統(tǒng)有效的全網(wǎng)整合營銷推廣解決方案,現(xiàn)已廣泛運(yùn)用于各行各業(yè)的客戶,其中包括:成都水電改造等企業(yè),備受客戶稱揚(yáng)。
vue作為前端的框架,node(express)作為后端的框架。無數(shù)據(jù)庫,使用端口保存數(shù)據(jù)。 VUE:
使用vue-cli構(gòu)建vue項目(vueapp)。
npm install -g vue-cli(安裝,安裝過的就不用了) vue init webpack vueapp
axios:(與ajax相似)
import axios from 'axios' var url="http://localhost:3000" //express服務(wù)器的地址 axios.get(url+'/product') //放數(shù)據(jù)的接口 .then(function (response) { //收到的數(shù)據(jù) console.log(response); console.log(response.data); //展示數(shù)據(jù)(看看是否拿到,和數(shù)據(jù)長啥樣) var nodeData=response.data; }) .catch(function (error) { console.log(error); });
axios沒安裝的記得裝一下。(安裝不細(xì)說)
node(express): 啟動>>>npm start
使用express構(gòu)建服務(wù)器:
新建個myapp放express npm install express
在(routes文件夾中)建一個product,js接口
var express = require('express'); //使用express var router = express.Router(); //放數(shù)據(jù) /* GET home page. */ router.get('/', function (req, res, next) { var data = { code: 0, data: { name: 'aaa', pwd: '123' }, isSuccess: true, msg: "請求成功" } res.json(data); }); module.exports = router;
app.js(建立接口存放數(shù)據(jù))
var productRouter = require('./routes/product'); app.use('/product', productRouter);
最后服務(wù)器數(shù)據(jù)有了?。。?!VUE前端接收數(shù)據(jù)的鏈接也有了?。。〉€是沒辦法鏈接?。。?!這就是跨域的問題?。?!
跨域:
1.端口不同 http://localhost:3000和http://localhost:8080
2.網(wǎng)址不同 www.baidu.com和www.aiqiyi.com
3.ip和網(wǎng)址不同 http://localhost:3000和http://127.0.0.1
反正除非同個網(wǎng)址里面,只有目錄不同,才不用跨域。
開始解決?。?/p>
express>>>app.js
//跨域問題解決方面 const cors = require('cors'); app.use(cors({ origin:['http://localhost:8080'], methods:['GET','POST'], })); //跨域問題解決方面 app.all('*',function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:8080'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); next(); });
cors需要安裝,是一個依賴。
結(jié)果:
服務(wù)器(express):3000接口數(shù)據(jù)
看完了這篇文章,相信你對“VUE+node如何實現(xiàn)前后端分離”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!