....) Now , I want to make "po" /> ....) Now , I want to make "po" /> ....) Now , I want to make "po"/>

Make CRUD request with Nodejs

114 views Asked by At

I want to make ajax calls with nodeJS to an endpoint. I have done many "get" requests by doing

http.get('url', (res) => ....)

Now , I want to make "post, put and delete" request

For example, I would to like to do

http.post('url', 'body', (res) => ...)
http.put....
http.delete ...

When I did that http.post request, I obtain "TypeError: "listener" argument must be a function". And this is my complete request

http.post(environment.url , req.body, (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
        data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
        return res.status(200).send(JSON.parse(data))
    });

}).on("error", (err) => {
    res.status(404).send(err)
});

It is possible ? Many thanks

1

There are 1 answers

1
ShamPooSham On

For some reason NodeJS don't seem to implement the other HTTP methods as their own methods in the http module. You'll have to use http.request and set the request method in the option.

In its most simple form, you should be able to write

var req = http.request({method: 'POST', path: url}, (res) => ...);
req.write(body);
req.end();

Source: https://nodejs.org/api/http.html#http_http_request_options_callback