How to set a Header field on POST a form?
Asked Answered
O

8

123

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

Oft answered 1/3, 2012 at 13:14 Comment(3)
Using XmlHttpRequest you mean? Or just a plain HTML FORM post?Maintopmast
no, i'm using form action:postOft
possible duplicate of Custom HTTP Request headers in HTMLArdis
M
80

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
Maintopmast answered 1/3, 2012 at 13:20 Comment(6)
I can't use ajax in this case. Somehow, I'm Post and Redirect to a aspx page. Redirection is happen by From Post.Oft
My suggestion is to include either 1) a hidden form element 2) a query string parameterMaintopmast
Can you serialize files? I thought: No.Gilford
Yes you can serialize files into Base64 strings, perhaps very clumsy for huge files since Base64 can be quite bulky. But so is every serialization method.Gray
I'd just add it as a query string param & have your server check to see if a header or query string exists and has the token.Bustup
I can't understand how this UPDATE relates to the thing you previously said. Can you show an example?Branle
K
15

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.

Kuhn answered 20/8, 2013 at 20:16 Comment(1)
Note: If the header you want to add is for CSRF protection, make sure you do not store that token in a cookie, or you'll defeat the CSRF protection.Solitude
D
6

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.

Dippold answered 1/10, 2015 at 15:29 Comment(0)
E
2

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.

Eschew answered 1/3, 2018 at 18:22 Comment(1)
And also make sure that you protect against CSRF owasp.org/www-community/attacks/csrfRafflesia
S
1

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
Scorbutic answered 23/3, 2017 at 15:15 Comment(0)
O
0

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.

Omnidirectional answered 1/3, 2012 at 13:28 Comment(3)
I use this form submit to redirect to an aspx page and post some data.Oft
make me understand better: 1) user posts 2) saving data 3) redirect. Is it what you do?Omnidirectional
I've an iFrame in an Html page(Source), pointing to another html page(Proxy). Proxy page post some parameter (No Get) via a form element. Redirection and post happens on form submit. I retrieve posted parameters in aspx page as destination.Oft
O
-3

To add into every ajax request, I have answered it here: https://mcmap.net/q/17825/-how-to-add-header-authorization-for-post-form-using-js-ajax-jquery


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://mcmap.net/q/17826/-jquery-form-submit-adding-request-headers

Orelle answered 21/11, 2019 at 0:57 Comment(0)
M
-3

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

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

Source: https://mcmap.net/q/17827/-setting-headers-when-using-jquery-form-plugin

Mercantilism answered 21/8, 2020 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.