How to set a Header field on POST a form?

JavascriptHtmlPostHttp PostHttprequest

Javascript Problem Overview


How can I set a custom field in POST header on submit a form?

Javascript Solutions


Solution 1 - Javascript

It cannot be done - AFAIK.

However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.

Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.

UPDATE

My suggestion is to include either

  • a hidden form element
  • a query string parameter

Solution 2 - Javascript

Set a cookie value on the page, and then read it back server side.

You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.

Solution 3 - Javascript

From FormData documention:

> XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.

With an XMLHttpRequest you can set the custom headers and then do the POST.

Solution 4 - Javascript

In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.

In node-js, you can set up and use cookies with cookie-parser.

an example:

res.cookie('token', "xyz....", { httpOnly: true });

Now you can access this :

app.get('/',function(req, res){
 var token = req.cookies.token
});

Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it. If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.

Solution 5 - Javascript

Here is what I did in pub/jade

extends layout
block content
    script(src="/jquery/dist/jquery.js")
    script.
      function doThePost() {
        var jqXHR = $.ajax({ 
            type:'post'
            , url:<blabla>
            , headers: { 
                'x-custom1': 'blabla'
                , 'x-custom2': 'blabla'
                , 'content-type': 'application/json'
            }
            , data: {
                'id': 123456, blabla
            }
        })
        .done(function(data, status, req) { console.log("done", data, status, req); })
        .fail(function(req, status, err) { console.log("fail", req, status, err); });
      }
    h1= title
    button(onclick='doThePost()') Click

Solution 6 - Javascript

You could use $.ajax to avoid the natural behaviour of <form method="POST">. You could, for example, add an event to the submission button and treat the POST request as AJAX.

Solution 7 - Javascript

To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708


To add into particular ajax requests, this' how I implemented:

var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
 method: "POST",
 beforeSend: function(xhr) {
  xhr.setRequestHeader(token_header, token_value);
 },
 data: {form_field: $("#form_field").val()},
 success: doSomethingFunction,
 dataType: "json"
});

You must add the meta elements in the JSP, e.g.

<html>
<head>        
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <meta name="_csrf" content="${_csrf.token}"/>

To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708

Solution 8 - Javascript

If you are using JQuery with Form plugin, you can use:

$('#myForm').ajaxSubmit({
    headers: {
        "foo": "bar"
    }
});

Source: https://stackoverflow.com/a/31955515/9469069

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReza OwliaeiView Question on Stackoverflow
Solution 1 - JavascriptAliostadView Answer on Stackoverflow
Solution 2 - JavascriptChris HynesView Answer on Stackoverflow
Solution 3 - JavascriptMajidView Answer on Stackoverflow
Solution 4 - JavascriptRamesh PareekView Answer on Stackoverflow
Solution 5 - JavascriptSteveView Answer on Stackoverflow
Solution 6 - JavascriptFabio BudaView Answer on Stackoverflow
Solution 7 - JavascriptHimadri PantView Answer on Stackoverflow
Solution 8 - Javascriptsm7View Answer on Stackoverflow