Axios傳送Ajax請求
阿新 • • 發佈:2021-07-14
axios.html
- get
- post
- 通用
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>axios傳送ajax請求</title> <script crossorgin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script> </head> <body> <!-- 210323 --> <button>GET</button> <button>POST</button> <button>AJAX</button> <script> const btn = document.querySelectorAll('button'); //配置baseURL axios.defaults.baseURL = 'http://127.0.0.1:8000'; btn[0].onclick = function () { //GET 請求 axios.get('/axios-server', { //url params: { id: 100, vip: 7 }, //請求頭資訊 headers: { name: '123', age: 20 } }).then(value => { console.log(value); }); } btn[1].onclick = function () { //引數1:url,引數2:請求體,引數3:其他配置 axios.post('/axios-server', { username: 'admin', password: '123' }, { //url params: { id: 200, vip: 9 }, headers: { height: 180, weight: 150 } }) } //通用方式 btn[2].onclick = function () { axios({ //請求方法 method: 'POST', //url url: 'axios-server', //url引數 params: { vip: 10, level: 30 }, //頭資訊 headers: { a: 100, b: 100 }, //請求體引數 data: { username: 'phy', password: 234 } }).then(response => { console.log(response); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.data); })//then處理 } </script> </body> </html>
server.js
//axios服務 app.all('/axios-server', (request, response) => { //設定響應頭 設定允許跨域 response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Allow-Headers', '*') //設定響應體 // response.send('Hello Axios Ajax'); const data = { name: 'phy' }; response.send(JSON.stringify(data)); });