Here is my server side code: (I use Laravel framework)
// route
Route::post('get_login_api_token', 'Auth\LoginController@get_login_api_token')->middleware('cors');
public function get_login_api_token(Request $request){
return $request;
}
And here is three kind of requests:
fetch('https://back.pronexo.net/get_login_api_token', {
method: 'POST', // or 'PUT'
mode: 'no-cors',
body: JSON.stringify({cell_phone:'whatever', password:'whatever'}),
headers:{
'Content-Type': 'application/json',
},
}).then(res => console.log('OK'));
returns
[]
fetch('https://back.pronexo.net/get_login_api_token?cell_phone=whatever&password=whatever', {
method: 'POST', // or 'PUT'
mode: 'no-cors',
headers:{
'Content-Type': 'application/json',
},
}).then(res => console.log('OK'));
returns
{"cell_phone":"whatever","password":"whatever"}
Ok, as you can see, in the postman (request simulator) it works when when you pass parameters in the body
section (not as query string in the url). But why it doesn't work in the code? (you can try it in the console
tan of your browser). Any idea how can I make #1
working ?
EDIT: Noted that the header is different in the postman:
I didn't use header as application/json and didn't encoded body with json format.
I have used curl and i am getting response in json and when decoded it gives
stdClass Object ( [cell_phone] => whatever [pass] => whatever )
Are you sure that the POST requets is well formated ?
I think that you should test using the FormData API (doc).
var data = new FormData
data.append("cellphone", "whatever")
data.append("password", "whatever")
// using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://back.pronexo.net/get_login_api_token')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function() {
if (xhr.readystate = 4 && xhr.status == 200) {
console.log(xhr.response, xhr.responseText)
}
}
xhr.send(data)
// using fetch method I don't know how it deals with FormData Objects.
fetch('https://back.pronexo.net/get_login_api_token', {
method: 'POST', // or 'PUT'
mode: 'no-cors',
body: data,
headers:{
'Content-Type': 'application/json',
},
}).then(res => console.log('OK'));
You can maybe use external tools like this: Insomnia REST Client to test your API.