I am using angular 4 for one of my projects and i have a method which creates a form element dynamically and submits it
postToUrl(path, params, method) {
method = method || 'post';
let form = document.createElement('form');
form.setAttribute('method', method);
form.setAttribute('action', path);
for (let key in params) {
if (params && params.hasOwnProperty(key)) {
let hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
setTimeout(() => {
document.body.removeChild(form);
}, 2000);
}
What i want to do is set a custom header to the request so that i can attach all the headers required by the server. Is there any way i can write a common interceptor for this so that i don't have to repeat the lines. Please help. Any help is appreciated.
I can't understand your requirement completely but if you are using angular then you can add and intercept headers (client side) via HTTPClient module
Here is another answer that might help you.
https://stackoverflow.com/a/47393331/6841216
Related
Please consider the following code snippet :
function dynamicallyPostForm(path, params, method = 'post') {
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
dynamicallyPostForm('/contact/', {name: 'Johnny Bravo'});
How to set Request Header XSRF-TOKEN? :
(tips : my project in asp.net mvc core and used [ValidateAntiForgeryToken] in controller)
Short answer is No. There is no browser-side facility for setting arbitrary HTTP Request Headers when submitting a form.
Besides, if you don't have any special setting in asp.net core. The ValidateAntiForgeryToken will check the formdata's __RequestVerificationToken instead of the header XSRF-TOKEN.
This is how validate AntiForgery works:
1.The client requests an HTML page that contains a form.
2.The server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
3.When the client submits the form, it must send both tokens back to the server. The client sends the cookie token as a cookie, and it sends the form token inside the form data. (A browser client automatically does this when the user submits the form.)
4.If a request does not include both tokens, the server disallows the request.
So the most easily way is set the token as the hidden field and postback like below:
#Html.AntiForgeryToken()
<input type="button" onclick="dynamicallyPostForm('TestWithAnti', {name: 'Johnny Bravo'});" />
#section scripts{
<script>
function dynamicallyPostForm(path, params, method = 'post') {
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
//get the token and append into new form
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = '__RequestVerificationToken';
hiddenField.value = document.getElementsByName('__RequestVerificationToken')[0].value;
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
</script>
}
Result:
I have several User Controls and one of which requires a click to go to a different page. I have a javascript function that is called and with the alert within, I know it's posting the correct data. Also this Javascript call is used with other websites and is working fine, but they are not dealing with user controls. The user control, calls ShowNotes, but posting to a normal form page with a site.master page. I'm thinking I'm missing something simple, so please be kind and let me know what I'm missing.
function ShowNotes(appName, serverName, appDataID) {
var params = [];
params.push({
AppName: appName,
ServerName: serverName,
AppDataID: appDataID
});
formPost("/Notes.aspx", params);
}
function formPost(url, params) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("name", "hiddenForm");
form.setAttribute("action", url);
var hiddenField;
for (var key in params) {
for (var val in params[key]) {
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", val);
hiddenField.setAttribute("value", params[key][val]);
form.appendChild(hiddenField);
//alert(val + ": " + params[key][val]);
}
}
document.body.appendChild(form);
form.submit();
}
Then on the Notes.aspx side, I debug and show the Request.Form.Count = 0. What can I possibly be missing? I also looked at the request.QueryString and it's empty.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Form.Count > 0)
{
EDIT:
Based on VDWWD comment, I modified the method to check if a form exists and use that one. I'm still getting the same results.
function formPost(url, params) {
var form = document.forms[0];
if (form == undefined) {
form = document.createElement("form");
form.setAttribute("name", "hiddenForm");
form.setAttribute("id", "hiddenForm");
}
alert(form.id);
form.setAttribute("method", "post");
form.setAttribute("action", url);
var hiddenField;
for (var key in params) {
for (var val in params[key]) {
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", val);
hiddenField.setAttribute("value", params[key][val]);
form.appendChild(hiddenField);
//alert(val + ": " + params[key][val]);
}
}
document.body.appendChild(form);
form.submit();
}
I started researching this 301 Moved Permanently and found that people stating, to change the post to just the page without the extension. The 301 is redirecting the page without the extension, causing the POST data to not be passed.
So I changed my JavaScript to remove the .aspx and put a slash in it's place and it works, even through it's a ASPX page:
function ShowNotes(appName, serverName, appDataID) {
var params = [];
params.push({
AppName: appName,
ServerName: serverName,
AppDataID: appDataID
});
formPost("/Notes/", params);
}
I tested the following simplified snippet from your edit after my comment.
<script type="text/javascript">
function formPost(url, params) {
var form = document.forms[0];
form.setAttribute("method", "post");
form.setAttribute("action", '/default.aspx');
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", 'FormPostTest');
hiddenField.setAttribute("value", "TheValueOfTheHiddenField");
form.appendChild(hiddenField);
form.submit();
}
</script>
And on Default.aspx I retrieve the value with this Request.Form["FormPostTest"] and it works just fine. Even if the post page is different from the page the form is on.
Are you sure you are posting to the correct page and with the correct name?
I made a webcam page in Laravel5.
I would like to send POST(javascript, WEBCAMjs) to crop.blade.php(laravel).
My code works well when run with only php.
=> form.setAttribute("action", "crop.php");
However, if I try to send it to laravel(crop.blade.php), it returns MethodNotAllowedHttpException.
=> form.setAttribute("action", "crop.blade.php");
How can I solve this problem?
thanks for your help in advance!
Webcam.snap( function(data_uri) {
var obj1 = data_uri
var form = document.createElement("form");
form.setAttribute("charset", "UTF-8");
form.setAttribute("method", "Post");
#form.setAttribute("action", "crop.php");
form.setAttribute("action", "crop.blade.php");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "raw");
hiddenField.setAttribute("value", obj1);
form.appendChild(hiddenField);
var url ="crop"
var status = "toolbar=no,directories=no,scrollbars=no,resizable=no,status=no,menubar=no,width=1240, height=1200, top=0,left=20"
document.body.appendChild(form);
form.submit();
}
It will be the routing. If you go to your web.php file, you will see the route that you are loading for the page. It might look like the following:
Route::get('crop', function () {
return view('crop');
});
You also need the following to allow post requests
Route::post('crop', function () {
// Logic for the post request
});
Obviously it would be better to use controllers instead of closures, but that's the general idea.
i am using angular 2/4 for one of my projects and i am in a situation where i have to download a file on submitting the request. I am doing currently.
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let blob = new Blob([data.body], { 'type': 'application/octet-stream' });
saveAs(blob, 'file.zip');
})
The file size could be very huge so i want the browser to handle the request instead of parsing the data and creating a blob in the application side. So i read somewhere that we can create a form element dynamically and give the handle to the browser instead of letting the application handle the blob and storing in the memory. So i tried
post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("token", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
This doesnt seem to be working, the page always redirects to some error page. So my query is, how to download a huge file without hanging the browser. Please help.
The problem was i was doing
hiddenField.setAttribute("token", key);
instead of
hiddenField.setAttribute("name", key);
Changing to the name solved my issue
Maybe simply generate link to downloading file on post:
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let link = data.body; // //http://path/to/file;
window.open(link);
// or
var link = document.createElement('a');
link.href = link
link.click();
});
I have the following code that gets executed when button is pressed.
function signInButton(){
var data = {
"userName" : $("#text_userName").val(),
"password" : $("#password_signInPassword").val()
};
var userName = $("#text_userName").val();
var password = $("#password_signInPassword").val();
var loadUrl= parentApp + "/executeLogin.htm";
makeNetCall(loadUrl, data, function(responseJson) {
jQuery("#text_userName").val('');
jQuery("#password_signInPassword").val('');
post('/TestWebProject/pages/SetSession.jsp', {name: 'Johnny Bravo'});
},
function(err) {
jQuery("#text_userName").val('');
jQuery("#password_signInPassword").val('');
alert("Invalid Username/Password");
});
}
but this post request post('/TestWebProject/pages/SetSession.jsp', {name: 'Johnny Bravo'}); is getting aborted.
post method is
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
There is no other request that could abort my post request. Why is this happening then? Any has encountered this before? solution/workaround?
Read NS_BINDING_ABORTED Javascript window.location.replace()
Based on your network output, it looks like you are redirecting to the login while the post is still going on. I'm not sure what the code of makeNetCall looks like, but I assume something in there is causing the page to change before the form is even done loading.