安装
cnpm i axios -S
发送get请求
方法一:
在axios方法中直接传入一个对象,配置请求路径:url,
传递参数:params。然后使用。.then方法获得响应数据
//配置接口地址axios.defaults.baseURL = 'http://127.0.0.1:3000'function testget() {axios({url: '/a',params: {id: 1}}).then(response => {console.log('/a', response.data)return response.data}, error => {console.log('错误', error.message)})}testget()
方法二:
function testget() {axios.get('/a?id=1').then(response => {console.log('/a', response.data)})}
post请求
方法一:
function testpost() {axios.post('/a', {"id": 5,"name": "ssss"}).then(response => {console.log('/a1', response.data)}, error => {console.log('错误', error.message)})}testpost()
方法二:
function testpost() {axios({method: 'POST',url: '/a',data: {id: 1,name: "张三"}}).then(response => {console.log('/a', response.data)return response.data}, error => {console.log('错误', error.message)})}testpost()
说明:post请求中,使用data传递信息
js服务器代码
var express = require('express')var path = require('path')var bodyParser = require('body-parser')const { json } = require('body-parser')var app = express()app.use(express.static(path.join(__dirname, 'public')))app.use(bodyParser.urlencoded({ extended: false }))app.use(bodyParser.json())app.get('/a', function(req, res) {console.log(req.query)res.send({ "id": 1, "name": "张三" })})app.listen(3000, function() {console.log('app is runing...')})
如果觉得《使用axios发送get和post请求》对你有帮助,请点赞、收藏,并留下你的观点哦!