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

How to send a POST request? (example) #570

Closed
frzsombor opened this issue Feb 26, 2021 · 2 comments
Closed

How to send a POST request? (example) #570

frzsombor opened this issue Feb 26, 2021 · 2 comments
Labels
usage help [Use a Discussion instead]

Comments

@frzsombor
Copy link

frzsombor commented Feb 26, 2021

Hi! Can someone please provide a working POST request example?
I've been struggling with sending a simple POST request with undici for hours.
Tried adding post data to body several ways, but the server is not getting it.
Tested with https://postman-echo.com/ too, native POST request succeeds, but undici is not.

Is there anything wrong with this code?

const { Client } = require('undici');
const client = new Client(`https://example.com`);
const qs  = require('querystring');

client.request({
  path: '/path/to/post',
  method: 'POST',
  headers: {
    myheader: 'value'
  },
  body: qs.stringify({
    data1: true,
    data2: 'asd'
  })
}, function (err, data) {
  //...
})
@Ethan-Arrowood
Copy link
Collaborator

Hi @frzsombor this might be an issue with your server. Here is an example I coded up that successfully posts a string to a native Node.js http server

'use strict'
const { createServer } = require('http')
const { Client } = require('undici')

const server = createServer((request, response) => {
  request.setEncoding('utf8')
  request.on('data', console.log)

  response.end('undici')
})

server.listen(() => {
  const client = new Client(`http://localhost:${server.address().port}`)

  client.request({
    path: '/',
    method: 'POST',
    headers: {
      myHeader: 'value'
    },
    body: '?data1=true&data2=asd'
  }, (err, data) => {
    const { body } = data
    body.setEncoding('utf8')
    body.on('data', console.log)
  })
})

@Ethan-Arrowood Ethan-Arrowood added the usage help [Use a Discussion instead] label Mar 2, 2021
@frzsombor frzsombor changed the title POST request is not working (or I'm doing it wrong) How to send a POST request? (example) Mar 3, 2021
@frzsombor
Copy link
Author

Thanks for the quick, detailed help! I haven't had time to test it yet, but I already noticed that I've missed the first question mark '?' character from the beginning of the data string, maybe that caused the issue. I've modified the title of the issue to be more search friendly for those who are looking for a POST example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
usage help [Use a Discussion instead]
Projects
None yet
Development

No branches or pull requests

2 participants