Emulate Python HTTP request using JS Fetch - javascript

I can successfully do a simple HTTP request using python requests:
def renew_token():
"""
Send a request to renew the login token
"""
url = url
fields = {
"username": "username",
"password": "password"
}
r = requests.post(url, data=fields)
print(r)
I am trying to do the exact same request using javascript fetch, but with no luck.
async function renewToken(url = '', fields = {}) {
const response = await fetch(url, {
method: 'POST'
data: JSON.stringify(fields),
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
//'Content-Type': 'application/x-www-form-urlencoded',
},
});
return await response.json();
}
renewToken('url', { username: 'username', password: 'password' })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
The error I get back is :
{ data: null,
message: 'No username or password provided',
status: 'api-error' }
which implies there is something wrong with the content type. I've tried changing the content-type to 'application/x-www-form-urlencoded', but I get the same error.
What am I missing to emulate the python request using fetch?

Had to use form data , not sent data in body:
async function renewToken(url = '', fields = {}) {
const response = await fetch(url, {
method: 'POST', //
body: 'username=username&password=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return await response.json();
}

Related

Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't

I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});

Localhost express mongodb server, fetch request to localhost returns 400 status

const data = {
email: "paul#Smith.com",
password: "PaulPass"
}
const body = JSON.stringify(data)
const paramsPost = {
method: "POST",
body: body
}
async function fetchContent() {
console.log(paramsPost)
let res = await fetch("http://localhost:3000/api/user/login", paramsPost);
console.log(res)
When I make run this function and fetch the response the console log prints out:
Response {type: "cors", url: "http://localhost:3000/api/user/login", redirected: false, status: 400, ok: false, …}
Could you tell me why it is doing this? What did I do wrong? When I make the request on postman the request gives me a status 200 and returns a JWT.
Thank you,
Snow
Changing the params to this:
const paramsPost = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: body
}
gives status 200!
I guess this is the answer but its very unsatisfying as what I wanted was the res.header
It's still undefined.

How to logout the authenticated token correctly after API call returns response?

I have the below code on client side, on click event It sends a request server side node to get a token, then when token is returned from external url response. It passes that token onto the second ajax call to call a specific api route.
This all works great, but I want to logout the token after I get the response from a specific api route (using the token). So that after the response I don't have the token staying alive.
What would be a good way to accomplish this? My current solution is when the response for the specific api route is given, send a fetch request to /tokenrequest/logout to logout the token. But not sure if that is a correct or good way to do it.
getdata.addEventListener("click", function(e) { //simple button click to initiate api
e.preventDefault();
$.ajax({
method: "GET",
url: "/jdeapi",
error: function(request, status, error) {
console.log(error);
}
}).then(function(data) {
console.log(JSON.parse(data));
let rawData = JSON.parse(data);
var token = rawData.userInfo.token;
$.ajax({
method: "POST",
url: "/sendtojde",
data: {
token
}
}).then(function(data) {
console.log(data);
})
})
})
The node server side code is as follows for the token request
router.get('/jdeapi', function(req, res) {
let url = 'https://Aisserver:port/jderest/tokenrequest';
let data = {
username: 'username',
password: 'password',
deviceName: 'riolivApp'
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text => res.json(text));
})
Then after the 2nd ajax call on client side, the server side call to fetch a specific api is as follows
router.post('/sendtojde', function(req, res) {
console.log(req.body.token);
let url = "https://Aisserver:port/jderest/poservice"
let data = {
token: req.body.token,
deviceName: 'riolivApp',
applicationName: "P4310",
version: "RMI0001"
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text =>
res.json(text));
})

ReactJS- Pass the JWT token as Authorization in axios method for http request

I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues.
My code-
getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}
I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.
Create instance of your axios,
const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});
And then call this function to set headers dynamically
agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;
Then call methods of your axios instance to make API calls
agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),

Getting access token with axios

I'm working with the Lyft API, and trying to figure out how to get an access token with axios with a node script.
I can manually get an access token by using Postman by filling out the form like this:
When I fill out the form, I can get a new token from Lyft successfully.
I'm trying to translate this into a POST request using axios by doing this:
var axios = require('axios');
var data = {
"grant_type": "client_credentials",
"scope": "public",
"client_id": "XXXXXXXXX",
"client_secret": "XXXXXXXX"
};
var url = "https://api.lyft.com/oauth/token";
return axios.post(url, data)
.then(function(response){
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
When I run the script, I get this error:
{ error_description: 'Unauthorized', error: 'invalid_client' }
What am I missing from my axios request? Any help would be appreciated!
According to the docs from Lyft (https://developer.lyft.com/docs/authentication), you need to use HTTP Basic auth.
var axios = require("axios");
axios.request({
url: "/oauth/token",
method: "post",
baseURL: "https://api.lyft.com/",
auth: {
username: "vaf7vX0LpsL5",
password: "pVEosNa5TuK2x7UBG_ZlONonDsgJc3L1"
},
data: {
"grant_type": "client_credentials",
"scope": "public"
}
}).then(function(res) {
console.log(res);
});
Happy coding :)
!IMPORTANT THING!
I strongly recommend you to change your secret_id and client_secret asap, because they are not the things to be public, if you use them for an important project or something like that.
I have solved my problem with this code.
var reqData = "grant_type=password&username=test&password=asd";
Axios({
method: 'post',
url: 'http://localhost:60439/token',
data: (reqData),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then((response) =>{
console.log(response)
}).catch((error) =>{
console.log(error);
})
The Best solution was source using the following way. The client sends a POST request with following body parameters to the authorization server
grant_type with the value client_credentials
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
axios.post('https://exmaple.com/oauth/token',
'grant_type=client_credentials&scope=all&client_id=1&client_secret=bb'
)
.then(function(res) {
console.log(res);
})
.catch(error => {
console.log(error)
})
const axios = require("axios");
const qs = require("qs");
const url = "URL";
const data = {
grant_type: "client_credentials",
};
const auth = {
username: "Client ID",
password: "Client Secret",
};
const options = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify(data),
auth: auth,
url,
};
axios(options)
.then((response) => {
console.log(response.data.access_token);
})
.catch((err) => {
console.log(err);
});
The following works. I got it by reading the above comments. The trick was the data field. To be clear use - data: "grant_type=client_credentials"
Example:
const axios = require("axios");
axios.request({
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
url: "/oauth2/token",
method: "post",
baseURL: "https://<ServerFQDN>/",
data: "grant_type=client_credentials",
auth: {
username: "<username>",
password: "<password>"
}
});

Categories

Resources