AJAX学习日记九

一、AJAX-fetch()函数发送AJAX请求

fetch函数是属于全局变量的,返回值为一个promise对象

前端代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>fetch 发送 AJAX请求</title>
    </head>
    <body>
        <button>AJAX请求</button>
        <script>
            const btn = document.querySelectorAll('button');
            btn[0].onclick = function(){
                fetch('http://127.0.0.1:8000/fetch-server?vip=10',{
                    //请求方法
                    method:'POST',
                    //请求头
                    headers:{
                        name:'autiguigu'
                    },
                    //请求体
                    body: 'username=admin&password=admin'

                }).then(response=>{
                    //return response.text();
                    return response.json();//json对象
                }).then(response=>{
                    console.log(response);
                });
            }
        </script>
    </body>
</html>

服务端代码

//fetch 服务
app.all('/fetch-server',(request,response)=>{
    //设置响应头 设置允许跨越
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    //第四个参数类型的演示
    const data={name: '尚硅谷'};
    response.send(JSON.stringify(data));
    // response.send('Hello jQuery AJAX');
});

二、AJAX-同源策略

ajax默认遵循同源策略

同源策略:最早由Netscape公司提出,是浏览器的一种安全策略。

同源:协议、域名、端口号 必须完全相同。

违背同源策略就是跨域。

前端代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>首页</title>
    </head>
    <body>
        <h1>hello</h1>
        <button>点击获取用户数据</button>
        <script>
            const btn = document.querySelector('button');
            btn.onclick = function(){
                const x = new XMLHttpRequest();
                //因为这里是同源策略的,所以url可以简写
                //
                x.open("GET",'/data');
                //发送
                x.send();
                //
                x.onreadystatechange = function(){
                    if(x.readyState ===4 ){
                        if(x.status >=200&&x.status<300){
                            console.log(x.response);
                        }
                    }
                }
            }
        </script>
    </body>
</html>

服务端代码

//1.引入express
const { request } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/home',(request,response)=>{
    //设置响应
    response.sendFile(__dirname+'/index.html');
});
app.get('/data',(request,response)=>{
    response.send('用户数据');
});
//4.监听端口服务
app.listen(9000,()=>{
    console.log('服务器已经启动,9000端口监听中...');
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值