Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node 请求实现 GET 支持携带 body #46

Closed
francecil opened this issue Jul 1, 2021 · 1 comment
Closed

Node 请求实现 GET 支持携带 body #46

francecil opened this issue Jul 1, 2021 · 1 comment
Labels
JavaScript JS相关面试、笔试题,不涉及算法

Comments

@francecil
Copy link
Owner

背景

get 也是支持携带 body 的,只是社区认为这个是一种不好的实践,因此像 node-fetch 以及浏览器的 fetch 都明确要求 get 请求里 body 必须为 null

fetch 认为这种实践不好,不提供此功能以避免此实践滥用

见:whatwg/fetch#551

我同意 fetch 的看法,但是对于某些遗留接口,怎么临时绕过呢?常用的 node-fetch/axios 都不支持 get 请求携带 body

另注:curl 默认是支持的

curl -X GET https://x.com/api/a \
--data-raw '{"a": 1}'
@francecil francecil added the JavaScript JS相关面试、笔试题,不涉及算法 label Jul 1, 2021
@francecil
Copy link
Owner Author

const urlParse = require('url').parse;
const https = require('https');
const http = require('http');

const requestWithBody = async (url, options = {}) => {
    return new Promise((resolve, reject) => {
        const callback = function (response) {
            let str = '';
            response.on('data', function (chunk) {
                str += chunk;
            });
            response.on('end', function () {
                resolve(JSON.parse(str));
            });
        };
        const urlOptions = urlParse(url, true)
        const req = (urlOptions.protocol === 'https:' ? https : http).request({
            host: urlOptions.host,
            port: urlOptions.port,
            protocol: urlOptions.protocol,
            path: urlOptions.path,
            method: options.method || 'GET',
            headers: {
                ...options.headers,
                ...(options.body ? {
                    'Content-Length': options.body.length
                } : null)
            }
        }, callback);
        req.on('error', (e) => {
            reject(e);
        });
        options.body && req.write(options.body);
        req.end();
    });
};

使用方法:

const body = JSON.stringify({
    "projectId": "138",
})
const result = await requestWithBody('https://path.to.com/api/xx/ss', {
    body,
    headers: {
       'token': 'abc'
   }
})

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JS相关面试、笔试题,不涉及算法
Projects
None yet
Development

No branches or pull requests

1 participant