Store session from initial login via POST? - javascript

I am running nodeJS and have the following function:
const fetch = require("node-fetch");
async function createCustomer() {
let response = await fetch('https://sampleurl.com/login', {
method: 'POST',
body: 'username=usernameHere&password=passwordHere',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar = await response.json();
console.log(tempVar);
This logs in and authenticates, providing me a successful response.
However if I then try and do the next step, it fails with an unauthorized error.
let response2 = await fetch('https://sampleurl.com/list', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar2 = await response2.json();
console.log(tempVar2);
In python I use requests.Session() and do the initial authorization and then any API call after that just begins with 'session' and it works. For example::
session = requests.Session()
session.post('https://sampleurl.com/login',data={'username':'usernameHere','password':'passwordHere'})
response = session.get('https://sampleurl.com/list').json()
print(response)
This is the functionality I am trying to replicate, but I can't figure out how to store the session.
Any help would be much appreciated.
Edit: Using Express.
Edit2: This is not hitting an API I am running the server for, I am not looking for how to build this feature as the API server, rather just connect to an external API.

Related

GitHub API authorization works with node-fetch v2 but not with v3

I have the following fetch request that works fine with node-fetch v2.6.0:
const url = "https://github.developer.mycompany.io/api/v3/search/code?q=%3Cnxt+extension%3Ats+extension%3Ahtml+repo%3Aawesome/repo&per_page=100"
const options = {
agent: undefined,
method: 'GET',
headers: {
Authorization: 'Basic toookenn',
'Content-type': 'application/json',
Cookie: 'yummycookie'
}
}
response = await fetch(url, options);
const data = await response.json();
But when I update to the current node-fetch v3.2.9 the authorization fails and I only get the HTML of the login page as response.
I could not find any changes regarding headers or authorization in the node-fetch v2 to v3 upgrade guide.
Does anyone know what's the problem here?

read CSV coming from rest-api in Angular-8

I have a rest-api which is returning csv file, how can i get it in the angular service.
getCSV() {
let headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+ "7woNSuuEYqLfQAuqwHhCJn8aq2SM"
});
const httpOptions = {
headers: headers_object,
Accept: 'text/csv'
};
this._http.get(
'https://00.00.xx.00:9001/abcd/export', httpOptions
).subscribe(resp => {
console.log(resp)
}
);
}
Data is coming in network tab, but angular goes into the ERROR status saying http failure during parsing for because somehow it is expecting the json return.
Please help
Headers in POSTMAN as attached in image.

using http with axios return 400 with request it works

I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.

npm start gets 401 and node app.js gets 200 response

I have a React project that I run with npm start and this code gets 401 Error from the second fetch (the first one is ok). It runs fine returning 200 only with node, like in "node App.js".
So what would I need to do to run my React project getting 200 response? Why is there this difference between npm and node to this request response?
const clientID = <ClientID>
const clientSecret = <ClientSecret>
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${encode}`,
},
};
fetch("https://auth-nato.auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", requestOptions)
.then(response => { return response.json() })
.then(data => {
const requestOptions2 = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json',
'Authorization': `Bearer ${data.access_token}`
},
body: '{"username":"Ana", "password":"test123","user_id":"ana#email.com"}'
};
fetch('https://j1r07lanr6.execute-api.sa-east-1.amazonaws.com/v1/register', requestOptions2)
.then(response => {console.log(response)});
})
Buffer - is not presented in the browser's javascript.
Instead of
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
use just
const encode = btoa(`${clientID}:${clientSecret}`);
Read more about base64 encoding on MDN.
I found out it was a CORS issue that needed to be set correctly on the back-end. My workaround was disabling chrome web security and removing "mode: no-cors".
I've tried adding "Access-Control-Allow-Origin":"http://localhost:3000" to headers but it doesn't work.

How can I send a request like in python and return the site response?

Why my code in js dont sends the post data and in python works ?
In js
const options = {
url: "https://asd.com",
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client',
'data': {"user.login":"login","user.senha":"pass"}
}
};
request(options, function(err, resx, body) {
console.log(resx);
res.send(body)
});
In python
import requests
data = {
"user.login":"login",
"user.senha":"pass"
}
r = requests.post('https://asd.com', params=data)
print(r.text)
I just want to send a custom form without json format, but it never works.
to make POST request in vanilla JS:
fetch("https://asd.com", {
method: 'POST',
body: {"user.login":"login","user.senha":"pass"},
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client',
}
}).then(res => res.json())
I suggest you also to read about the fetch API so It won't be hard for you anymore to make any other kind of request in JS https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

Categories

Resources