I have a function which sends a POST request to my node.js server, but the headers, params, cookies and everything is empty. I've checked my browser console and it was sent, there's just nothing in it. Can anyone help my identify the problem? (email and pass isn't empty, either.)
function sendPostRequest() {
const email = document.getElementById('email').value;
const pass = document.getElementById('pass').value;
var params = 'email=' + email + "&pass=" + pass;
var http = new XMLHttpRequest();
http.open("POST", "http://localhost:3000", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
}
Follow the steps to fix the error
Check network tab in browser developer console whether it's passing the data or not if not the problem is in front end.
If that is true, then check backend and print the request body if there it's not coming then it's backend
Related
I am trying to send a post request to a Flask server that uses flask_jwt_extended tokens. I don’t want the page to refresh after each submit and I managed to do this using jquery. But I am unable to send CSRF token in a way that flask_jwt_extended can authenticate user.
function myfunction(action, id, csrf_token){
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:5000/accept", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
action: action,
id: id,
csrf_token: csrf_token
}));
}
$(document).ready(function() {
$(document).on('click', '#my-form', function(event) {
var action = $(event.target).attr('value');
var f = $(this);
csrf_token = f.find('input[id=csrf_token]');
myfunction(action, f.find('[name=song_id]').val(), csrf_token)
return false;
});
});
#app.route('/accept', methods=["POST"])
#jwt_required
def accept():
user = get_jwt_identity()
...
When I try the following I get a 401 error, which is not surprising as I am not passing the csrf token as in a form. If I simply submit a post request on the form, it works fine.
EDIT:
On my backend I am using the following setting for flask_jwt_extended:
app.secret_key = 'loginner'
app.config['JWT_SECRET_KEY'] = 'super-secret'
app.config['JWT_TOKEN_LOCATION'] = ['cookies', 'headers']
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
app.config['JWT_COOKIE_CSRF_PROTECT'] = False # the bearer request works when this is False, but ideally it would be True
app.config['JWT_CSRF_CHECK_FORM'] = True
And I am getting the identify in the following:
#app.route('/accept', methods=["POST"])
#jwt_required
def accept():
user = get_jwt_identity()
...
It works as expected when app.config['JWT_COOKIE_CSRF_PROTECT'] = False
Your question does not specify how you are handling the JWT on the client side, but the basic answer is that you need to pass an Authorization header with your request (see more near the bottom of the page in your flask_jwt_extended docs). There may be some confusion in that CSRF and identity are not the same thing. CSRF just helps your frontend and API understand that they can trust each other. A package like flask_jwt_extended helps your backend identify the user and authorize requests.
In your client example above, you would add another header line as such:
// the 'jwt' variable refers to however you have stored the token. Change as needed
xhr.setRequestHeader('Authorization', 'Bearer ' + jwt);
I have started with the minehut API, and after looking at the docs (see a copy here) it uses get and post.
As a newbie to javascript etc I dont know how it works.
Part 1 - Get Info
for example: I want to get info about a server, it says to use GET https://api.minehut.com/server/{server-id}
How would i get for example playercount from it so that i can give that info to my code and display it on my website.
Required headers: is also mentioned in the docs, what are these and how do i use them?
Part 2 - send info
Now say for example i want to run a command, the docs say to use POST /server/{Server ID}/send_command. It also mentions Required headers saying it needs
Content-Type,
Authorization and
x-session-id
how would i send a string so that it would use POST to run a command
What you need to send or receive data using GET/POST methods is XMLHttpRequest object.
var server_id = "EXAMPLE_ID";
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(this.readyState == 4){
// Data sent back available in this.responseText
// For example:
var recData = this.responseText;
// further handling
}
}
req.open('GET', 'https://api.minehut.com/server/' + server_id, true);
req.send();
Or in case of POST request:
req.open('POST', 'https://api.minehut.com/server/' + server_id + '/send_command', true);
req.setRequestHeader("Content-Type", "pplication/x-www-form-urlencoded");
req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
req.setRequestHeader("HeaderNameExample", "ItsValueExample");
req.send('optionalVar=sentData&foo=bar&etc");
In some cases preflight request can be done (especially with custom request headers) and the request might fail. To avoid that you might try invoking the opening with user/password instead. For cross domain request Access-Controll request should be made which allows for cookies to be set.
req.open("GET", url, true, username, password);
req.open("POST", url, true, username, password);
req.withCredentials = true;
I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);
I have a JavaScript code that is supposed to send some data to a php file on the server. The JavaScript code gives an alert that the post was successful, but no data is on the php file. No errors show up in the console. What is the problem here?
Here is the code:
var data = "It works";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert("It worked");
}
}
http.send(data);
Here is the site for the code:
http://mikeyrichards.freeiz.com/run.html
EDIT: A clarification, I only want the data to show up like a text file on the PHP. For some reason, my server cannot open text files, so I have to use PHP
You need to send data in key value format something like this
var data = "lorem=ipsum&name=test";
Try changing to:
var data = 'data=It+works';
Then you can access it in the PHP script as $_POST['data'].
Don't forget to encode the space as + or %20. If you're generating the data dynamically, use encodeURIComponent to encode it properly:
var data = 'data=' + encodeURIComponent(value);