How to Send Query Params in GET and POST in JavaScript - Webtips

PHOTO EMBED

Wed Apr 05 2023 17:11:20 GMT+0000 (Coordinated Universal Time)

Saved by @mindplumber #javascript #fetch

const post = async (url, params) => {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(params),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        }
    })

    const data = await response.json()

    return data
}

// Then use it like so with async/await:
(async () => {
    const data = await post('https://jsonplaceholder.typicode.com/posts', {
        title: 'This will be the title',
        body: 'Setting the body property',
        userId: 1
    })

    console.log(data)
})()

// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
    title: 'This will be the title',
    body: 'Setting the body property',
    userId: 1,
}).then(data => console.log(data))
content_copyCOPY

https://webtips.dev/solutions/send-query-params-in-get-and-post-in-javascript