在 node 中使用 jquery ajax

对于前端同学来说,ajax 请求应该不会陌生。jquery 真的ajax请求做了封装,可以通过下面的方式发送一个请求并获取相应结果:

$.ajax({
    url: "https://echo.apipost.cn/get.php",
    data: formData,
    type: "POST",
    processData: false,
    contentType: false,
    success: function (data, status, xhr) {
        console.log(data, status, xhr)
    },
    error: function (xhr, status, error) {
        console.log(xhr, status, error)
    },
    complete: function (xhr, status) {
        console.log(xhr, status)
    }
})

但是,在 node 环境中,就需要一些其他库实现接口发送,例如GOT、request 等。当然,也可以通过在node 中安装 jquery 来使用上面 $.ajax 的方法,但是会有一个很要命的问题:跨域。

何为跨域?

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。也就是违反了“同源策略”:

同源策略是一个重要的安全策略,它用于限制一个origin的文档或它加载的脚本如何能与另一个源的资源进行交互。能够减少恶意文档,减少可能被攻击媒介。 如果两个URL的协议、域名、端口号都相同,就称这两个URL同源。

浏览器默认两个不同的源之间是可以互相访问资源和操作DOM的。两个不同的源之间若是想要访问资源或者操作DOM,那么会有一套基础的安全策略的制约,我们把这称为同源策略。它的存在可以保护用户隐私信息,防止身份伪造。

使用 ajax-for-node 实现 $.ajax

ajax-for-node (https://github.com/Apipost-Team/nodeajax)是一个在 node 环境下实现 .ajax的库,它的所有参数格式和.ajax 的库,它的所有参数格式和 .ajax的库,它的所有参数格式和.ajax 完全一致。

const nodeAjax = require('ajax-for-node');

var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);

nodeAjax({
    url: "https://echo.apipost.cn/get.php",
    data: formData,
    type: "POST",
    processData: false,
    contentType: false,
    success: function (data, status, xhr) {
        console.log(data, status, xhr)
    },
    error: function (xhr, status, error) {
        console.log(xhr, status, error)
    },
    complete: function (xhr, status) {
        console.log(xhr, status)
    }
});

npm 搜 ajax-for-node

展开阅读全文

页面更新:2024-05-12

标签:协议   策略   参数   两个   操作   格式   文档   环境   域名   资源

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top