Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters in NodeJS' sync-request

I have tried the following:

var request = require('sync-request');

var res = request('POST', 'http://someurl.com', {

  body: {

    'city': 'Dubai'

  }

});

But didn't get any parameters on the Server.

like image 618
Ahsan Avatar asked Sep 16 '26 19:09

Ahsan


2 Answers

I have solved it myself (by modifying the Options as follows):

var request = require('sync-request');

var res = request('POST', 'http://someurl.com', {

  headers: {       
    'content-type': 'application/x-www-form-urlencoded'
  },

  body: 'city=Dubai'

});

It works well.

like image 56
Ahsan Avatar answered Sep 19 '26 13:09

Ahsan


If you want a strongly-typed client, you can try out ts-sync-request.

NPM: https://www.npmjs.com/package/ts-sync-request

This library is a wrapper around sync-request.

You can attach a header & make a request like below:

import { SyncRequestClient } from 'ts-sync-request/dist'
let url = "http://someurl.com";

let response = new SyncRequestClient()
                            .addHeader("content-type", "application/x-www-form-urlencoded")
                        .post<string, MyResponseModel>(url, "city=Dubai"); 
like image 43
Cliff Avatar answered Sep 19 '26 12:09

Cliff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!