I am using the below code to get the data back from API and it works fine. I have another API which is secured one and that requires a user name / password to access the content and I am not sure how to pass in the credentials when using isomorphic fetch module. Can someone help?
I am using this module: https://www.npmjs.com/package/isomorphic-fetch
I need to pass in username and password as below (Sample curl command)
curl -u admin:hello123 http://test:8765/select?q=*
Code:
fetch(
url
).then(function (response) {
if (response.status != 200) {
dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url))
}
return response.json();
}).then(function (json) {
dispatch(setData(json, q))
}).catch(function(err){
});
Most APIs would used a POST request for authentication. They expect as well to receive the data to validate (user/password). Also, they usually require extra information in the header like to specify the format (e.g. application/json) of the data (the user/password data) you are sending. You are not passing any of that. Check below something that might work, but it all depends of what the API you are hitting is expecting (check its documentation).
fetch(url, {
method: 'POST',
headers: {
// Check what headers the API needs. A couple of usuals right below
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// Validation data coming from a form usually
email: email,
password: password
}
}).then(function (response) {
if (response.status != 200) {
dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url))
}
return response.json();
}).then(function (json) {
dispatch(setData(json, q))
}).catch(function(err){
console.log(err);
};
Related
I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298
first time poster, excited to have a community to collaborate with here!
So here's my situation. I'm using Node to put together an automation for my company's compliance - taking reports from our MDM server and posting them to our compliance platform (Tugboat Logic). The idea is to have it deployed on a recurring basis via AWS Lambda. The basic logic is this: getToken fetches an auth token which is then passed to getReports. getReports loops through an array of endpoints to get reports from the MDM and then passes those along to fileReport - which then posts that data to the endpoint.
The problem is that the final endpoint needs a file as the payload (sample POST request below). I managed to get the whole fetch chain working by using fs writeFile/readFile (and a delay), and while that worked, it doesn't translate well into a Lambda environment. Ideally, I want to just take the payload from getReports (which comes through as JSON but can also be accepted as text) and push it straight to the endpoint. Any help on how I could clean up this code would be appreciated!
Here's the bit giving me the most trouble (from the last file)
form.append('file', x, `${reportsArray[i].name}.json`);
// Sample post request for final endpoint
curl -v --user <provided-username>:<given-password> \
-H "X-API-KEY: <given-x-api-key>" \
-F "collected=<date-of-evidence>" -F "file=#<local_filename_csv>;type=text/csv" \
<given-collector-url>
//getReports.js accepts a token from an earlier function and takes fileReport as the cb
function getReports(token, cb) {
const headers = {
method: 'GET',
headers: {
'accept': 'application/json',
'Authorization': `Bearer ${token}`
},
redirect: 'follow'
}
for (let i = 0; i < reportsArray.length; i++) {
fetch(reportsArray[i].source, headers)
.then(res => res.json())
// writeFile leftover from successful deploy
/*.then(data => fs.writeFile(`./reports/${reportsArray[i].name}.json`, data, function (err) {
if (err) throw err;
}))*/
.then(res => cb(i, res))
.catch(error => console.log('error', error))
}
};
//fileReport.js - i identifies the right endpoint from the imported array and sets filename. x is the JSON payload passed down from getReports
function fileReport(i, x) {
const form = new FormData();
form.append('collected', getTimestamp());
form.append('file', x, `${reportsArray[i].name}.json`);
fetch(`${reportsArray[i].dest}`, {
method: 'POST',
headers: {
'X-API-KEY': `${process.env.TUGBOAT_X_API_KEY}`,
'Authorization': 'Basic ' + btoa(`${process.env.TUGBOAT_USERNAME}:${process.env.TUGBOAT_PASSWORD}`)
},
body: form
});
};
I have a node server which gets an access token from Spotify's Web API. The response looks like this:
Response:
{
"statusCode": 200,
"body": "{\"type\":\"success\",\"done\":{\"json\":{\"access_token\":\"BQDqtYhVpafUIMYtZbwmy6iJcC_wvzR9Xrw6bRDFfpL3zZYfkCp2-KZaQVS-ZoElMF1czAl_B1vEaDrtPBOElSV3D5k\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"scope\":\"user-top-read\"}}}",
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"
}
}
When I try to use the access_token on Spotify's online API tool, I get an error for incomplete JSON. I think this is because the token I generate is only 91 characters long while the code they generate is 171 characters long. Why is my auth code so short?
I want an access token so I can use this react module for accessing my top tracks.
Here is my code for getting the access token:
let getAccessToken = (queryStringParameters) => {
let url = 'https://accounts.spotify.com/api/token';
let encoded = (new Buffer(client_id + ':' + client_secret).toString('base64'));
console.log("encoded = " + encoded);
let params = {
grant_type: 'authorization_code',
username: username,
password: password,
scope: scope
};
const formParams = Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
return fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Basic ' + encoded,
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formParams
})
.then((response) => {
console.log(util.inspect(response, { showHidden: true, depth: null }));
return response.json();
})
.catch((error) => {
done({
error: error
});
});
};
According to the Authorisation Guide the authorization_code grant type only takes the code and redirect URI values. Not sure why the username and password ones you provide are even accepted, it is possible the token returned is a client credentials one as those tend to be shorter, that only access non-user related endpoints like loading Artist data, but the parameters you're providing appear to be undocumented at least in that guide.
I have tried everything and can't get Axios to work with SAP Odata Post services. The problem is CSRF token validation failing but its working fine in Postman.
My request looks like this:
const postNewTasks = async (body, headers) => (await axios.get(getHeadersandCFRSURL, {
headers: { 'authorization': auth, 'x-csrf-token': 'fetch' },
withCredentials: true
}).then((response) => {
axios({
method: 'POST',
url: postBatchOperationsURL,
headers: {
"Authorization": auth,
"Content-Type": "multipart/mixed; boundary=batch_1",
"X-CSRF-Token": response.headers["x-csrf-token"], // set CSRF Token for post or update
},
withCredentials: true,
body: body
}).then(function (response) {
console.log(response)
return response
}).catch(function (err) {
console.log(err)
return err
})
})
)
Anybody has idea why the CSRF token validation fails with this axios request?
I had this issue recently and a solution that worked for me was to add a Cookie header with the cookies from the initial response set-cookie headers.
Postman does this automatically, but axios doesn't it would seem. My code from that part after "x-csrf-token":"fetch":
var xcsrftoken = response.headers["x-csrf-token"];
var cookies = '"';
for (var i = 0; i < response.headers["set-cookie"].length; i++) {
cookies += response.headers["set-cookie"][i] + ";";
}
cookies += '"';
axiosClient.defaults.headers.common[this.xcsrftokenName] = xcsrftoken;
axiosClient.defaults.headers.common["Cookie"] = cookies;
axiosClient is the object made from axios.create. I've set those headers as default so that I don't need to include them later in the requests. There were multiple set-cookie headers as well and it was necessary to combine them into one.
that is my code in helper signin router
so I'm trying to set cookie to browser after confirm sign in
exports.signin = (req,res) => {
db.User.findOne({email:req.body.email}).then(user => {
user.comparePassword(req.body.password,function(err,isMatch){
if(isMatch){
let token = jwt.sign({userId: user.id},process.env.SECRET_KEY,{ expiresIn: 60*5 });
res.setHeader() //here I wanna send header Bearer to the browser
} else {
res.status(400).json({message:"Incorrect Password!"});
}
})
})
.catch(err => {
return res.status(404).send('No user found.');
})**strong text**
}
Authorization header is a client header, you cannot set it on the server(Server does not need authorization). You need to send it in a JSON response and then handle it in the client side.
Your server sends a JSON response with the token.
Your client sets the Authorization header and send it to any route that reaquires authorization
javascript client example:
var myHeaders = new Headers()
/**you need to get the token and put it in myToken var.
Where to store the token is the real question, you need
to take care about the storage you choose beacause of
the security risks*/
myHeaders.append('Content-Type','application/json; charset=utf-8');
myHeaders.append('Authorization', 'Bearer ' + myToken);
fetch( '/myurl', {
credentials: 'include',
headers: myHeaders,
method: 'GET'
}).then( res => {
return res.json();
}).then( res => {
/**your stuff*/
});
Then in your server check for the headers and you will see the Bearer
In Node.js res.setHeader() and Express js res.header() is an alias of res.set() method.
you can use in following ways :
res.setHeader('Authorization', 'Bearer '+ token);
res.header('Authorization', 'Bearer '+ token);
But I recommend you to read jwt example (angularjs & node) : https://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs--cms-22543