初始化目录结构 npm init -y
下载express npm i express
利用 express 搭建服务器
//创建服务器 //第一个引入express框架 const express = require(‘express‘) //第二 把express 方法付给app const app = express() //创建一个接口,当用户访问‘/‘ app.get(‘/‘,(req,res)=>{ res.send(‘当前服务器已连接‘) }) app.get(‘/foodList‘,(req,res)=>{ const json = [ { id:1, name:‘海底捞‘ }, { id:2, name:‘水煮鱼‘ }, { id:3, name:‘烧烤‘ }, ] res.send(json) }) //第三步监听我的端口 app.listen(3000)
4.启动服务
***注意*** 但凡app.js有修改记得重启服务器(node搭建的服务器)
创建项目命令 vue init webpack mydemo(项目)
初始化项目,删除你该删除的内容
下载axios http库 npm i axios
创建组件
在组件中调取接口
import axios from ‘axios‘ export default { mounted() {//生命周期函数,挂载 //组件一加载就调取美食列表接口 axios({ url:‘/api/foodList‘, // params:{} //method:‘get‘ get方法可以省略 }) .then((res)=>{ console.log(res,‘响应‘) }) .catch((err)=>{ }) }, }
如果产生跨域问题(解决跨域问题)
配置config文件夹 => index.js文件
proxyTable: {//利用代理服务器去解决跨域问题(本地开发的时候)vue中的方法 ‘/api‘:{ //‘/api‘ 地址是自己定义的 target:‘http://localhost:3000‘, //你要解决跨域的地址 changeOrigin:true,//在本地搭建一个虚拟服务,去发送种请求拦截服务 pathRewrite:{//地址重写 ‘^/api‘:‘http://localhost:3000‘ } } },
//引入axios库 import axios from ‘axios‘ //把axios挂载到Vue原型 Vue.prototype.http = axios
song.vue组件
this.http.post(‘/api/postInfo‘) .then(res=>{ console.log(res,‘成功之后的响应‘) this.list = res.data }) .catch(err=>{})
`npm install(i) jquery`
如果全局引入:
import jquery from ‘jquery‘
Vue.prototype.jq = jquery
原文:https://www.cnblogs.com/ly1368489670/p/12758558.html