6

I need to hit an api using "require" npm in node. The api requires raw put data (not put fields). How do I do this using request npm?

example raw put data I need to send:

var body = {
   "id": 123,
   "squares": [
       {
           square_id: 345,
           color: "#ccc"
       },
       {
           square_id: 777,
           color: "#fff"
       }
   ]
}

I'm trying this but it's not working:

        request({
            method: "PUT",
            uri: UPDATE_GAME,
            multipart: [{
                'content-type': 'application/json',
                body: JSON.stringify(body)
            }]
        }

2 Answers 2

9

If you dig into the code, you'll see that for the most basic of POST/PUT operations you can use the json options parameter. It will also do the JSON.stringify() for you - your code becomes simply:

request({
  method: "PUT",
  uri: UPDATE_GAME,
  json: body
 });
Sign up to request clarification or add additional context in comments.

3 Comments

How to get the body ,response and error from the put call after it gets executed ? @Michael Angstadt
You can pass a 2nd param of a callback matching cb = function(err, response, body){} so something like request(opts, cb)
@Michael Angstadt there are difference in PUT and PATCH request, PUT: take whole object in the body and update all fields. PATCH: take only that properties which you want updates, in that case whole object of json no need to send in patch request. how do we send data into patch request?
1

body is a JavaScript object. You are claiming to be sending JSON.

Pass it through JSON.stringify().

1 Comment

Right, I made a mistake when munging the code to post it here. It does stringify the json. Fixed the original post...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.