VUE+node(express)實(shí)現(xiàn)前后端分離
vue作為前端的框架,node(express)作為后端的框架。無數(shù)據(jù)庫,使用端口保存數(shù)據(jù)。 VUE:
使用vue-cli構(gòu)建vue項(xiàng)目(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): 啟動(dòng)>>>npm start
使用express構(gòu)建服務(wù)器:

新建個(gè)myapp放express npm install express
在(routes文件夾中)建一個(gè)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: "請(qǐng)求成功"
}
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
反正除非同個(gè)網(wǎng)址里面,只有目錄不同,才不用跨域。
開始解決??!
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需要安裝,是一個(gè)依賴。
結(jié)果:
服務(wù)器(express):3000接口數(shù)據(jù)


搞定了,以上就是本次介紹的全部知識(shí)點(diǎn),感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。
相關(guān)文章
Vue.js 中 axios 跨域訪問錯(cuò)誤問題及解決方法
這篇文章主要介紹了Vue.js 中 axios 跨域訪問錯(cuò)誤問題及解決方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2018-11-11
Vue2.0設(shè)置全局樣式(less/sass和css)
這篇文章主要為大家詳細(xì)介紹了Vue2.0設(shè)置全局樣式(less/sass和css),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
vue如何解決循環(huán)引用組件報(bào)錯(cuò)的問題
這篇文章主要介紹了vue如何解決循環(huán)引用組件報(bào)錯(cuò)的問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09
VSCode搭建vue項(xiàng)目的實(shí)現(xiàn)步驟
本文主要介紹了VSCode搭建vue項(xiàng)目的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

