XMLHttpRequest is requesting the wrong page - javascript

I'm trying to create a request that will send a user's information to my server to login. However, every time I try to send the request, it returns information about the page it's currently on /login.php, not the information from the api page /api/login.php.
function login_listener(){
let headers = parse_response_headers(this.getAllResponseHeaders());
if("response" in headers){
let error = document.getElementById("server_response");
error.hidden = false;
error.innerText = headers["response"];
return;
}
//window.location = headers["location"];
}
function login(){
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let auth_code = document.getElementById("auth_code").value;
const req = new XMLHttpRequest();
req.addEventListener("load", login_listener);
req.open("POST", "https://{MY_DOMAIN}/api/login.php", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(`username=${username}&password=${password}&auth_code=${auth_code}`);
req.onreadystatechange = () => {
console.log(req.getAllResponseHeaders());
}
}
function parse_response_headers(headers){
const arr = headers.trim().split(/[\r\n]+/);
const dct = {};
arr.forEach((line) => {
const parts = line.split(": ");
const header = parts.shift();
dct[header] = parts.join(': ');
});
return dct;
}
The login() function is called when the submit button on the form is clicked. I've checked the network tab in the developer tool pane, and each time I send the request to /api/login.php, it makes a call to /login first, and I can't see the response from the actual api.

Related

How can i catch the error when the api reaches its daily limit in JS?

I am trying to catch the specific error when a certain API key expires or it reaches its daily response limit(assuming 1000 per day).
const moviesearchEngine=()=>{
let searchBox = document.querySelector('.searchBox');
let movieTitle = document.querySelector('.movieTitle');
let yearofRelease = document.querySelector('.yearofRelease');
let genre = document.querySelector('.genre');
let director = document.querySelector('.director');
let plot = document.querySelector('.plot');
const apiCall = ()=>{
let params = new URLSearchParams({
t:searchBox.value,
apikey:`key`
})
let api = `http://www.omdbapi.com/?${params}`;
//fetching the api orelse showing the error
fetch(api).then((response)=>{
return response.json();
}).then((data)=>{
//assigning the data to variable
console.log(data)
})
}
apiCall();
}
Please Go through your desired API's documention and you would be looking for this sort of information mentioned in the Usage limits section of this api page. If you fail to find anything useful then please contact the support of your desired API.
Then you can proceed like this -
var endpoint = 'http://ip-api.com/json/?fields=status,message,countryCode';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
if(response.status !== 'success') {
console.log('query failed: ' + response.message);
return
}
// Redirect
if(response.countryCode == "US") {
window.location.replace("https://google.com/");
}
if(response.countryCode == "CA") {
window.location.replace("https://google.ca/");
}
}
};
xhr.open('GET', endpoint, true);
xhr.send();
Source

How to save value from a "upload.js" to request it in other .js

I've tried a lot of things to save the data from "request.responseText" to my var "pdf" that is a url with any file type and then call that variable containing the url into other .js that sends a string containing the rest of the form.
Here is the upload script
let pdf;
const uploadFile = (file) => {
console.log("Uploading file...");
const API_ENDPOINT = "https://file.io";
const request = new XMLHttpRequest();
const formData = new FormData();
request.open("POST", API_ENDPOINT, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
console.log("onreadystatechange request", request.responseText);
pdf = request.responseText;
console.log("pdf", pdf);
}
};
formData.append("file", file);
request.send(formData);
};
fileInput.addEventListener("change", (event) => {
var files = event.target.files;
uploadFile(files[0]);
});
and here is the "general form" which have to recieve the data from the form and send it as a string:
let result = document.querySelector(".result");
let name = document.querySelector("#form-name1");
let email = document.querySelector("#form-email1");
let phone = document.querySelector("#form-phone1");
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url ="yourapiurl";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
//Converting JSON data to string
var data = JSON.stringify({
name: name.value,
email: email.value,
phone: phone.value,
pdf,
});
console.log(data);
// Sending data with the request - not using it rn only console logs
// xhr.send(data); - not using it rn only console logs
//Clearing fields
document.getElementById("form-name1").value = "";
document.getElementById("form-email1").value = "";
document.getElementById("form-phone1").value = "";
document.getElementById("fileInput").value = "";
}
Sorry for any typo not native speaker of English and thanks if read.

django sending AJAx POST request using classical javascript into server with csrf_token, how to?

I have this part of code:
document.querySelector('#form_pizza_order').onsubmit = () => {
// make an ajax request to save the pizza order in the server
const request = new XMLHttpRequest();
request.open('POST', '/order_pizza');
// Callback function for when request completes
request.onload = () => {
const data = JSON.parse(request.responseText);
if (data.success) {
// show in cart new order
show_in_cart(data);
}
else {
alert('failed to save pizza order in server');
}
}
const data = new FormData();
let username = localStorage.getItem('username');
data.append('username', username);
//Send request
request.send(data);
return false;
};
that when used the server returns 403 forbidden response because of csrf_token not sent. how do I add the crsf_token header properly with the javascript above, without using jquery. just javascript.
thanks.
function sendData(){
const XHR = new XMLHttpRequest();
// Set up our request
XHR.open("POST", "{% url 'test:index' %}" );
XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Bind the FormData object and the form element
let FD = new FormData(form);
// append the token
FD.append('csrfmiddlewaretoken', '{{ csrf_token }}');
// The data sent is what the user provided in the form
XHR.send(FD);
}
let form = document.getElementById('<form_id>')
// take over its submit event.
form.addEventListener("submit", function (event) {
console.log('Submited!')
event.preventDefault();
sendData();
})
In your django views, you can test if the request is ajax:
def index(request):
if request.is_ajax() and request.method='POST':
print(request.POST)
# process post data
Django use X-Requested-With to detect an ajax request, take a look of How django detect ajax request
the sendData function is originated from Mozilla Docs
the following code made it happen:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sendData(){
const XHR = new XMLHttpRequest();
// Set up our request
var csrftoken = getCookie('csrftoken');
XHR.open("POST", "/order_pizza" );
XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
XHR.setRequestHeader('X-CSRFToken', csrftoken)
// Bind the FormData object and the form element
let FD = new FormData();
// append the token
FD.append('csrfmiddlewaretoken', csrftoken);
let username = localStorage.getItem('username');
FD.append('username', username);
// The data sent is what the user provided in the form
XHR.send(FD);
}
obviously we had to retrieve the csrf cookie first before we could use it as a form data.

csrf_token verification with Javascript XMLHttpRequest() (403 Forbidden)

i am trying to send a XMLHttpRequest() post request to the Django Server but it shows 403 Forbidden,
after searching i found that it is due to CSRF verification , after seeing lot of similar content still i am unable to figure out how to implement csrf in XMLHttpRequest
i am including the js snippet that i am using
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('click',event => {
if (event.target.id === "add-cart-button")
{ event.preventDefault();
const add_cart_button_id = event.target.dataset.pid
const item_class = event.target.dataset.type
const item_name = event.target.dataset.item
const size_chooser = `#${item_class}-size-${add_cart_button_id}`
var sel = document.querySelector(size_chooser)
const size = sel.value
const quantity_chooser = `#${item_class}-quantity-${add_cart_button_id}`
const quantity = document.querySelector(quantity_chooser).value
var request = new XMLHttpRequest()
request.open('POST','/addcart')
request.onload = () => {
const data = request.responseText
}
var data = new FormData()
data.append('iten_class',item_class)
data.append('item_name',item_name)
data.append('size',size)
data.append('quantity',quantity)
request.send(data)
}
})
})
i am sending this request to /addcart route of django server
def addcart(request):
return JsonResponse({'status':True})
which just returns this status
can anyone help me in csrf verification

Utilize same http session in javascript through many requests

In my backend I authenticate user once inlogging and then store the authenticated sessions at the server. Then after each user's request i check if the session associated with a request is stored as authenticated. The problem is that when I use JavaScript requests a new HTTP session is used each time i send something to my server written in Java.
When I use Postman everything is okay because it stores session through many requests.
//Here is authentication on server side - it works fine
#CrossOrigin
#RequestMapping(value= "/login", method = RequestMethod.POST)
public #ResponseBody String login(#RequestBody Account retrievedAccount,
HttpServletRequest httpServletRequest) {
if (retrievedAccount != null) {
Account account =
accountDAO.getAccountByLogin(retrievedAccount.getLogin());
if (account != null &&
account.getPassword().equals(retrievedAccount.getPassword())) {
this.registeredSessionsContainer.add(httpServletRequest.getSession());
return new ResponseEntity(HttpStatus.OK).toString();
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
}
Here is a simple way to check if a session is already authenticated:
#CrossOrigin
#RequestMapping(value= "/checkLogon", method = RequestMethod.GET)
public #ResponseBody String checkLogon(HttpServletRequest
httpServletRequest) {
if(this.registeredSessionsContainer.
contains(httpServletRequest.getSession()))
return new ResponseEntity(HttpStatus.OK).toString();
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
Here is how i login to service in my frontend JavaScript:
performLoggingToService(){
var login = document.getElementById("loginField").value;
var password = document.getElementById("passwordField").value;
var url = "http://localhost:8080/mvc1/login";
var method = "POST";
var crendentialsObject = { "login": login, "password": password };
var crendentialsObjectJSON = JSON.stringify(crendentialsObject);
console.log(crendentialsObjectJSON);
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(crendentialsObjectJSON);
//console.log("Is this undefined: "+(loginComponent==undefined));
var props = this.props;
var thisObjectPointer = this;
req.onload = function (e,thisObject=thisObjectPointer) {
var status = req.status; // HTTP response status, e.g., 200 for "200 OK"
var data = req.responseText; // Returned data
if(data.includes("200 OK")){
console.log("Checking LOGON STATE METHOD#2: ");
thisObject.props.refreshLogonStateInMainBand(login);
} else {
// inform user about wrong credentials
}
}
}
An then when i perform check if i am already logged in one address /checkLogon I use:
checkLogonState(currentUserName) {
console.log("CheckLogonState CALLED!");
var url = "http://localhost:8080/mvc1/checkLogon";
var method = "GET";
var req = new XMLHttpRequest();
var loginData;
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
}
req.send();
req.onreadystatechange=(e)=>{
if(req.readyState === 4 && req.responseText.length>0) {
if(req.responseText.includes("200 OK")){
console.log("Authenticated!!!");
this.changeMainComponentStateToLogin();
this.currentUserName = currentUserName;
this.oneTimeLogonCheckAction=false;
} else {
console.log("Not logged in!!!")
this.changeMainComponentStateToIdle();
this.currentUserName=undefined;
this.oneTimeLogonCheckAction=true;
}
this.forceUpdate();
}
}
}
As you may expect responseTest includes 404 Unauthorized not 200 OK.
I tried it on InternetExplorer, Microsoft Edge and Chrome. None of them reuses session.
After each of my requests console on server side shows that the requests are sent from other sessions - each request in a new session.
I would like to get to know how can I use same session if i use one the same browser window through many requests.
Set withCredentials to true for all XMLHttpRequest,
var req = new XMLHttpRequest();
req.withCredentials = true;
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(crendentialsObjectJSON);
will help to persist the session across calls.
At server side add this to all your controllers to solve cors issues,
#CrossOrigin(origins = ["http://localhost:3000"], allowCredentials = "true")

Categories