• Fetch发送请求 + 解决跨域问题 狼人:


     

    解决跨域问题:

    fetch()方法提供了一种简单,合理的方式来跨网络异步获取资源。

    可以使用fetch向服务器发送get请求或post请求来获取数据

    fetch的基本用法:
    fetch('/url').then(data=>{
    return data.text();
    }).then(ret=>{
    //注意,这里才是得到的最终数据
    console.log(ret);
    });
    使用fetch发送get请求:
    把参数拼接在url中传递过去

    text():将返回体处理成字符串类型

    json():返回结果和JSON.parse(responseText)一样

    fetch('http://localhost:3001/user/login?username='+zhanghao+'&&password='+mima)
    .then(function (response) {
    return response.text();
    })
    .then(function (myJson) {
    alert(myJson);
    });
    使用fetch发送post请求:
    fetch('http://localhost:3001/admin/add', {
    method: 'post',
    body:JSON.stringify(obj),
    headers:{
    'Content-Type': 'application/json'
    }
    })
    .then(function (response) {
    return response.text();
    })
    .then(function (myJson) {
    alert(myJson);
    });
    解决跨域问题:
    在服务器端添加 Response Header

    如果服务器返回的 response 头包含 “Access-Control-Allow-Origin:*” 或者 *为与请求源相同的地址。即服务器支持浏览器跨域访问。

    app.all("*",function(req,res,next){

    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

    next();
    })

    ————————————————
    版权声明:本文为CSDN博主「吃不到棒棒糖的小熊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/m0_59897687/article/details/124346869

  • 相关阅读:
    Premetheus告警QQ邮箱
    Prometheus+grafana监控SpringBoot2应用
    Grafana整合Prometheus
    Prometheus:入门初体验
    接口幂等性思路
    OpenFeign远程调用丢失请求头问题解决办法
    gradle构建脚本
    windows安装gradle
    CompletableFuture异步编排
    线程池(ThreadPoolExcutor)基本介绍
  • 原文地址:https://www.cnblogs.com/waw/p/16737743.html
Copyright © 2020-2023  润新知