|
# 前后端分离 2:传参
> Author: ZeXu > Soft: WebStrom > 前期准备: > 1. get:获取;post:增加;put:修改/编辑;delete:删除 > 2. 前端:get / delete 传参方式 基本相同;post / put 传参方式 基本相同 > 3. 后端:get / delete 接收方式 基本相同;post / put 接收方式 基本相同> > 在express和vue 1 的后端部分中,我们学会了如何制作一个简单的接口,当时前端使用的是 get 来发起请求,并未携带任何参数,在某些时候,我们在使用接口的时候需要传一些参数给后端,告诉后端你发起这个请求具体要做啥子事情。 > > 下面的代码块一定要看仔细,只有些许差别,很容易看错的 ## 后端如何接收到前端传来的参数 #### GET // # 参数在 query 里面 req.query // # 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); console.log(req.query) }); module.exports = route; #### Post // # 参数在 query 里面 req.body // # product.js (product名字是我任意取得) const express = require('express'); const route = express.Router(); route.post('/', (req, res, next) => { let data = { data: { name: 'ZeXu', pwd: '123' }, message: '请求成功!' }; res.json(data); console.log(req.body) }); module.exports = route; *** ## 前端如何向后端传参 > 这是 Express 和 Vue || 1 标题:查看 #### GET ``` javascript // # 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) }) // # 有参 axios.get('/product?name=123') .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) }) // # 多参 axios.get('/product?name=123&pwd=456') .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) }) ``` #### POST ``` javascript // # src > main.js import axios from 'axios' // let url = 'http:// localhost: 8000' // (url 已经在 config > index.js > module.exports > dev > proxyTable 设置了代理) // # 无参 axios.post('/product') .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) }) // # 有参 axios.post('/product', { name: 'ZeXu', pwd: '123' }) .then((response) => { console.log('response:', response) }) .catch((error) => { console.log('error:', error) }) ``` [ZeXu_于2020-07-17 12:41编辑了帖子]
|
|