csbukhari csbukhari - 1 year ago 82
HTML Question

NodeJS: How to use html form to send PATCH & DELETE request

I have an API and i should send PATCH request if i need to update the object; the problem is that when i send the PATCH request the body is always undefined.

this how i send PATCH request Ex.

app.patch('/applications/update/:application_id', function(request, response) {
var application_id = request.params.application_id;
require('../../models/applications/update_application_by_id').get(request.body, application_id, function(result){
response.render('applications/details', {application_details:result});

<form enctype="application/json" class="form-horizontal" role="form" method="post" action="/applications/update/{{application_details._id}}">
<input type="hidden" name="_method" value="PATCH" />
<input type="text" name="name" class="form-control">
<button type="submit" class="btn btn-yellow pull-right">update</button>

and this how i handle it

exports.get = function(request_body, application_id, call_back){
var http_request = unirest("patch", "https://xx/api/applications/"+application_id);

"cache-control": "no-cache",
"content-type": "application/json",
"x-application-key": "xxxxxxxxxxxxxxxxxx"


http_request.end(function (http_response) {
if (http_response.error) throw new Error(http_response.error);

return call_back(http_response.body);

Answer Source

so here we go,

i solve the problem by very easy way, since i'm talking with API so i have models files that talk with API so i defined my method on these files and make all the form as post and pass the post body as parmeter to models.

the example will explain more.

Model File:

var request = require("request");

exports.get = function(request_body, application_id, call_back){

    var options = {
        method: 'PATCH',
        url: 'http://XXXXXXXXXXXXXXXX'+ application_id,
           'content-type': 'application/json',
           'x-application-key': 'XXXXXXXXXXXXXXXXXXX'
        body: request_body,
        json: true

    request(options, function (error, response, body) {
      if (error) throw new Error(error);
      return call_back(body);


Controller File:

app.post('/applications/update/:application_id', function(request, response) {
    require('../../models/XXX/XXXX').get(request.body, request.params.application_id, function(result){
        response.render('XXXXX/details', {response_update:result});

Form Template:

<form class="form-horizontal" role="form" method="post" action="/applications/update/{{application.[0]._id}}">
    <div class="form-group">
        <div class="col-sm-4">
            <input type="text" name="name" class="form-control" value="{{application.[0].name}}" required>

<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
    <button type="submit" class="btn btn-yellow pull-right">update</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download