赞
踩
点击GET按钮,发送get请求;
点击POST按钮,发送post请求;
点击AJAX按钮,使用axios函数发送请求。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>ajax axios发送请求</title>
- <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
- <link crossorigin="anonymous" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu">
- <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.0/axios.js"></script>
- </head>
- <body>
- <div class="container">
- <h2 class="page-header">axios发送AJAX请求</h2>
- <button type="button" class="btn btn-primary">GET</button>
- <button type="button" class="btn btn-danger">POST</button>
- <button type="button" class="btn btn-info">AJAX</button>
- </div>
- <script>
- btn = document.querySelectorAll('button');
- // 配置baseURL
- axios.defaults.baseURL = 'http:127.0.0.1:8000';
- btn[0].onclick = function(){
- axios.get('/axios-server',{
- // url参数
- params: {
- name: 'xx',
- age: 20
- },
- // 请求头信息
- headers: {
- size: 123
- }
- }).then(value => {
- console.log(value);
- });
- };
- btn[1].onclick = function(){
- axios.post('/axios-server',{
- uname: 'admin'
- },{
- params: {
- id: 200
- },
- // 请求头参数
- headers: {
- height: 100,
- weight: 20
- }
- }).then(value => {
- console.log(value);
- })
- };
- btn[2].onclick = function(){
- axios({
- method: 'POST',
- url: '/axios-server',
- params: {
- vip: 11
- },
- headers: {
- a: 100,
- b: 30
- },
- data: {
- uname: 'admin'
- }
- }).then(response => {
- console.log(response.status);
- console.log(response.statusText);
- console.log(response.headers);
- console.log(response.data);
- })
- }
-
- </script>
- </body>
- </html>
- // 引入
- const { request } = require('express');
- // 创建应用对象
- const express = require('express');
- // 创建应用对象
- const app = express();
- // 创建路由规则
- app.all('/axios-server',(request,response) => {
- // 设置响应头 设置允许跨域
- response.setHeader('Access-Control-Allow-Origin','*');
- response.setHeader('Access-Control-Allow-Headers','*');
- const data = {name: 'xxx'};
- // 设置响应体
- response.send(JSON.stringify(data));
- });
- // 监听端口启动服务
- app.listen(8000,() => {
- console.log("服务已启动,8000端口监听中...");
- })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。