安装
cnpm i axios -S
方法一:
在axios方法中直接传入一个对象,配置请求路径:url,
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...')
})