Support Topics Documentation Slack YouTube Blog

Error on login


(Marco Rocchi) #1

Hello,
I’m implementing a login form that asks username and password.
The HTTP response i get is
{"code":17000,"message":"JSON parse error: 'Wrong JSON or ContentType.'.","errorData":{}}

and in the browser console i get the error Content Security Policy: Il caricamento di una risorsa su https://api.backendless.com/favicon.ico è stato bloccato dalle impostazioni della pagina (“default-src”).

This is the code of my login form

<html>
	<meta charset="utf-8">
	<form action= "https://api.backendless.com/<appid>/<rest key>/users/login" method="POST">
		<input type="text" name="login" value="a">username</input><br>
		<input type="password" name="password" value="segreta">password</input><br>
		<button type="submit" id="submit">Invia</button>
	</form>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script>
	$('#submit').on('click', function(){
		$.ajax({
			url:"https://api.backendless.com/<appid>/<rest key>/users/login",
			type: 'POST',
			contentType: 'application/json',
			headers:{
				"Content-Type": "application/json"
				},
			async: false
		})
	})
	</script>
</html>`

Obviously instead of appid and appkey i’ve put my id/key.

Thanks for helping


(Vladimir Upirov) #2

Hi Marco
There are a few reasons why it doesn’t work

  1. when you click at “sumbit” button there will be actually two requests, one from your form (it’s a native behavior) and another one from jQuery ajax, so, to solve the problem you have to prevent a submit event in you code

  2. the api server is expecting ContentType=application/json but the html form sends “application/x-www-form-urlencoded”

  3. in your code you don’t pass request body to ajax function

here is a working code

<html>
	<meta charset="utf-8">
	<form id="form">
		<input type="text" name="login" value="a">username</input><br>
		<input type="password" name="password" value="segreta">password</input><br>
		<button>Invia</button>
	</form>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script>
	$('#form').on('submit', function(e){
	  e.preventDefault() // prevent native form sending
	  
		$.ajax({
			url:"https://api.backendless.com/{APP_ID}/{API_KEY}/users/login",
			type: 'POST',
			contentType: 'application/json',
			data: JSON.stringify({ // request body should be stringified 
				login: e.target.login.value, // e.target=dom element (form); e.target.login=dom element (login input)
				password: e.target.password.value,
			})
		})
	})
	</script>
</html>

Regards, Vlad