首页 > 其他分享 >万象更新 Html5 - js: js 的跨域请求 XMLHttpRequest

万象更新 Html5 - js: js 的跨域请求 XMLHttpRequest

时间:2024-09-24 10:54:50浏览次数:1  
标签:Control XMLHttpRequest log Headers 万象更新 js Access xhr console

源码 https://github.com/webabcd/Html5
作者 webabcd

万象更新 Html5 - js: js 的跨域请求 XMLHttpRequest

示例如下:

js\XMLHttpRequest.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XMLHttpRequest</title>
</head>
<body>
<script>

    /**
     * CORS - Cross-origin resource sharing(跨域请求)
     * 所谓的跨域就是协议不同,或者域名不同,或者端口号不同
     * 为了支持跨域请求需要服务端对 response header 做如下配置
     *     Access-Control-Allow-Origin: *       // 配置允许访问的域名(默认无法跨域访问)
     *     Access-Control-Allow-Headers: *      // 配置支持的自定义的 request header
     *     Access-Control-Request-Method: *     // 配置支持的 http method(跨域时默认只支持 head, get, post)
     *     Access-Control-Expose-Headers: *     // 配置有权限获取的 response header(跨域时默认只能获取到 Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma)
     */

    let a = () => {
        // 实例化
        let xhr = new XMLHttpRequest();
        // 请求的超时时间(单位:毫秒)
        xhr.timeout = 30000;
        // 响应的数据格式(text, json, blob, arrayBuffer)
        xhr.responseType = "text";
        // 第 1 个参数:http method
        // 第 2 个参数:url
        // 第 3 个参数:是否是异步请求
        xhr.open('GET', 'http://localhost:42858/get_long', true);
        // 设置 request header(必须在 open() 之后指定,且必须是 Access-Control-Allow-Headers 允许的)
        xhr.setRequestHeader('api_key', 'value');
        xhr.onreadystatechange = function () {
            switch (xhr.readyState) {
                case 0:
                    console.log("UNSENT");
                    break;
                case 1:
                    console.log("OPENED");
                    break;
                case 2:
                    // 收到响应头
                    console.log("HEADERS_RECEIVED");
                    break;
                case 3:
                    // 正在下载响应体(一次请求可能会触发多次)
                    console.log("LOADING");
                    break;
                case 4:
                    // 请求结束,不管是成功还是失败
                    console.log("DONE");
                    break;
            }
        }
        // 请求完成
        xhr.onload = function (e) {
            // 遍历 response header(只能拿到有权限拿到的)
            let headers = this.getAllResponseHeaders();
            let arr = headers.trim().split(/[\r\n]+/);
            arr.forEach(function (line) {
                console.log(line);
            });

            // 获取指定的 response header(只能拿到有权限拿到的)
            console.log("Content-Type: " + xhr.getResponseHeader("Content-Type"));

            // status - 响应的 http 状态码
            // response - 响应的内容
            console.log(this.status, this.response);
        };
        // 请求超时
        xhr.ontimeout = function (e) {
            console.log("timeout");
        };
        // 请求失败
        xhr.onerror = function (e) {
            console.log("error");
        };
        // 下载进度发生变化
        xhr.onprogress = function (e) {
            // loaded - 已下载字节数
            // total - 总共字节数
            // timeStamp - 从开始请求到现在经历的时间(单位:毫秒)
            console.log(e.loaded, e.total, e.timeStamp);
        };

        // 开始请求
        xhr.send();
    }
    a();

</script>
</body>
</html>

WebApi\WebApi\ApiController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi
{
  public class ApiController : Controller
  {
    [Route("hello")]
    public IActionResult Hello()
    {
      return Content("hello webabcd", "text/plain", Encoding.UTF8);
    }

    [Route("get_long")]
    public async Task GetLong()
    {
      Response.Headers.Add("Access-Control-Allow-Origin", "*");
      Response.Headers.Add("Access-Control-Allow-Headers", "*");
      Response.Headers.Add("Access-Control-Request-Method", "*");
      Response.Headers.Add("Access-Control-Expose-Headers", "*");

      Response.ContentType = "text/html";
      Response.StatusCode = 200;
      Response.ContentLength = 10;

      for (int i = 0; i < 10; i++)
      {
        await Task.Delay(10);

        var content = "a";
        var data = Encoding.UTF8.GetBytes(content);
        await Response.Body.WriteAsync(data, 0, data.Length);
        await Response.Body.FlushAsync();
      }
    }

    [Route("jsonp")]
    public IActionResult Jsonp(string jsoncallback)
    {
      return Content(jsoncallback + "('hello jsonp');", "text/plain", Encoding.UTF8);
    }

    [Route("redirect")]
    public IActionResult Redirect()
    {
      return Redirect("https://www.cnblogs.com/webabcd/");
    }

    [Route("fetch")]
    public IActionResult Fetch()
    {
      Response.Headers.Add("Access-Control-Allow-Origin", "*");
      Response.Headers.Add("Access-Control-Allow-Headers", "*");

      return Content("{ \"name\": \"webabcd\" }", "application/json", Encoding.UTF8);
    }
  }
}

源码 https://github.com/webabcd/Html5
作者 webabcd

标签:Control,XMLHttpRequest,log,Headers,万象更新,js,Access,xhr,console
From: https://www.cnblogs.com/webabcd/p/18428663/html5_js_XMLHttpRequest

相关文章