javascriptnode.jsjsonnode-fetch

NodeJS - Send JSON object parameters with node-fetch


I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:

fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});

and

fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});

They both result in the following error:

{
    "message": "Validation Failed",
    "errors": [
        {
            "resource": "Hook",
            "code": "custom",
            "message": "Config must contain URL for webhooks"
        }
    ],
    "documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}

How do I properly send a JSON object? I'm looking for a solution using node-fetch


Solution

  • When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.

    So just add

    fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
        method: "POST",
        headers: {
            Accept: "application/vnd.github.v3+json",
            Authorization: `token ${account.accessToken}`
        },
        body:JSON.stringify(yourJSON) //here this is how you send your datas
    });
    

    And node-fetch will send your body with your request.

    If you want more details on that i'll expand my answer

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)