How to set a Header field on POST a form? - javascript

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

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

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.

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.

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.

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

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.

If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069

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

Related

How to send cookie in each request header in angularjs?

Hi I am in developing Angularjs web application. I am using API's to get data. On login successful i will get some data in cookie(response header). In very next subsequent http calls i need to send that back cookies data to apis. Below is the snapshot of response header.
Below is my sample $http call.
var req = {
method: 'POST',
url: savepersonaldetailsurl,
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
},
data: {
LoginId: LoginID
}
$http(req).then(function (response) {
//do something here
}, function (error) {
toastr.error($filter('translate')('Error Occured'));
});
On each http call i want to send cookie in header. May i know how this can be done in angularjs? Any help would be appreciated. Thank you.
One of the features of Cookies is that they're sent to the server with each request. Make sure that the domain the request is being made to is the same domain that set it or a sub domain.
The cookie is usually stored by the browser, and then the cookie is
sent with requests made to the same server inside a Cookie HTTP header
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
First store the value which comes from response in localstorage then secondly you can make a common global functions which set the value to localstorage and get the value and call that function on every request.
for example:-
headers: {
'Content-Type': 'application/json',
'Authorization': authfunction.getToken('AuthToken');
}
In this example i set the value in local storage named AuthToken and while passing it we get and set it.

html in jade/pug page needs a custom request header tag [duplicate]

How can I set a custom field in POST header on submit a form?
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
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.
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.
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.
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
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.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069
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

How to detect request type in Node Express JSON/HTML

I simply want to know if the request coming in is a standard page load or if the request has come from an ajax request.
Basically, I would like to use the same controller for both my ajax and my normal loading of a page.
Currently I am using:
console.info(req.get('Content-Type')); //undefined.
Here is the node code I am using
getFixtures: function (req, res) {
var passData = {}
console.info(req.get('Content-Type'));
passData.params = req.params;
leagues(app).getLeagues(passData)
.then(filterBarFixtures)
.then(function () {
res.render('games', {
title: 'Fixtures and Results',
passData: passData
})
});
}
app.get('/fixtures/', controllers.getFixtures);
2 way of loading the same controller
Open a browser and navigate to /fixtures
or
$.ajax({
method: "GET",
url: "/fixtures"
})
You would need to either set a header in the client request to look for in the server, or perhaps a search/query parameter
However, as you are using jQuery you don't need to worry
jQuery $.ajax uses XMLHttpRequest, which sets X-Requested-With=XMLHttpRequest request header
Additionally, if the request is for JSON (using $.ajax with appropriate settings or $.getJSON), jQuery usually sets Accept:application/json, text/javascript, etc
note, I've said "usually" to cover my butt in case in some strange browser this doesn't happen :p
Your comment regarding
beforeSend: function(request) { request.setRequestHeader("ajax",true); }
Is probably the safest option, as that header is guaranteed to be present, so that's the header to look for on the server side.

Modify XmlHttpRequest just inside one function of the code

I use a jQuery plugin named Redactor, which can send ajax requests (link to the code). My site has an ajax authentication using header. So, I need to set header of all ajax requests, sending via redactor.
How can I modify just this request of the website without modifying the source file?
P.S. I don't need to modify XmlHttpRequest globally. I want to modify it just for this chunk of code.
You can use ajaxSetup() ( https://api.jquery.com/jquery.ajaxsetup/ ). You can define default values for all ajax request in jQuery. So you can force the header to requests sent by Redactor.
See this question : How can I add a custom HTTP header to ajax request with js or jQuery?
If you want to add a header (or set of headers) to every request then
use the beforeSend hook with $.ajaxSetup():
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Navigate to URL with additional header

Is there anyway we can navigate (via <a/> click) to a URL with additional header in the request ? here's my code :
i have an <a href="#" id="aUsers"/> tag, and then i handle the onClick() event via JQuery :
$('#aUsers').click(function () {
var spAuthData = sessionStorage.getItem('sp-auth-data');
window.location.href = '/users.html?sp-auth-data' = spAuthData;
});
I want to put the spAuthData value in the authorization header, so i can have a clean URL
As far as I know, there is no way to manipulate HTTP headers with a plain url.
You can use headers parameter of jQuery AJAX request if it is suitable in your situation. For example, you can update the contents of some divs with AJAX HTML response.
$.ajax({
url: '/users.html',
headers: { 'Authorization': spAuthData }
}).done(function()
{
});
Otherwise, it looks like you need to make some server-side changes.
But why don't you use cookies or something like this?
Authorization is used only by unauthorized users during authorization. In my opinion, sending this header on every request from the browser manually sounds bad. The best approach is to send this header once during authorization, create a user session and store it in cookies (as an access-token, forms ticket or whatever else).

Categories

Resources