|
前后端分离 1:创建
Author: ZeXu Soft: WebStrom $ node -v
$ npm install cnpm -g --registry=https://registry.npm.taobao.org
Express 先检查一下 node 是否已经安装了,以及确认一下版本信息 node -v Create 创建
注意:是存在的文件夹
Fix & Listen Port 修改/监听 端口 // # app.js app.listen('8000', () => { console.log('服务已启动!') }) Router 制作一个接口: routes
// # product.js (product名字是我任意取得) const express = require('express'); const route = express.Router(); route.get('/', (req, res, next) => { let data = { data: { name: 'ZeXu', pwd: '123' }, message: '请求成功!' }; res.json(data); }); module.exports = route;
// # app.js const productRputer = require('./routes/product'); app.use('/product', productRouter); Start 启动 // # 在执行之前可以先 安装 CNPM,将 npm 换成 cnpm 已提高安装速度 $ npm start > $ cnpm start or package.json 文件 > 点击 start: 'node ./bin/www' 旁边的绿色箭头 > Run 'start' 浏览器地址栏中输入:localhost:8000 > 回车 Check API 测试一下刚才创建的接口 localhost:8000/product {"data":{"name":"ZeXu","pwd":"123"},"message":"请求成功!"} Vue-Cli Create 创建
注意: 不能是已存在的文件夹,他会帮你创建一个文件夹,如果是已存在的文件夹, webstorm 不会让你继续创建 vue.js 不能有大写
启动 安装 CNPM $ npm install cnpm -g --registry=https://registry.npm.taobao.org $ cnpm install 访问接口 访问 product 接口 $ cnpm install axios 安装完成后,记得去 package.json 文件中确认一下 axios 是否存在!如果不存在请看‘前期准备 3’ 引入 axios // # src > main.js import axios from 'axios' 连接后端并访问某个接口 // # src > main.js import axios from 'axios' let url = 'http:// localhost: 8000' axios.get(url + '/product') .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) }) 查看打开 控制台 查看是否成功拿到 数据 可是结果却不是这样的,接口访问不到,但是后台 有访问记录,且是 200 状态 这时候我们就该考虑是不是跨域导致的,是的话,我们需要设置一下代理 // # config > index.js > module.exports > dev > proxyTable proxyTable: { '/product': { target: 'http://192.168.10.xxx:8000', // # 后端服务器所在IP:端口 changeOrigin: true, // # 如果接口跨域的话就设置为 true secure: false // # 如果是 https 的话,需要设置为 true } } // # src > main.js import axios from 'axios' // let url = 'http:// localhost: 8000' // (url 已经在 config > index.js > module.exports > dev > proxyTable 设置了代理) axios.get('/product') .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) })
当前所在局域网访问 前端页面 如果你希望这个页面可以在其他人的电脑上看到,可以这么做: // # config > index.js > module.exports > dev > host host: '0.0.0.0' 这样,你所在局域网内的所有小伙伴都能通过你提供的地址访问到页面,并看到效果 补充 . 如果 api 的第一个总是不同的,那么需要设置多个代理 ``` javascript // # config > index.js > module.exports > dev > proxyTable proxyTable: { '/product': { target: 'http://192.168.10.xxx:8000', // # 后端服务器所在IP:端口 changeOrigin: true, // # 如果接口跨域的话就设置为 true secure: false // # 如果是 https 的话,需要设置为 true }, '/company': { target: 'http://192.168.10.xxx:8000', changeOrigin: true, secure: false }, } ``` [ZeXu_于2020-08-12 09:25编辑了帖子]
|
|