Axios sending url with params as string not object - axios

i need to take url with params example:
https://domain.pl/ptpdf-gen?selected_posts=4871&advisor=magda,wojciech
But axios response is an object like:
{"https://domain.pl/ptpdf-gen?selected_posts":"4871","advisor":"magda,wojciech"}
How to send url as string via axios?

Optionally the request above could also be done as
axios.get('/user', {
params: {
selected_posts: 4871
advisor: ["magda", "Wojciech"]
},
paramsSerializer: params => {
return qs.stringify(params)
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
The qs is an external library,
https://www.npmjs.com/package/qs

var selected = 4871
var advisor = ["magda","wojciech"]
axios.post('https://domain.pl/ptpdf-gen', {selected, advisor })

So i made the url split like this, using URLSearchParams:
const currHref = window.location.search;
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('selected_posts');
const myParam2 = urlParams.get('advisor');
Then with axios.post i can send params:
axios.post("http://domain.pl/create", {myParam, myParam2})
On server i did handle params like:
const state = req.body;
const stateValues = Object.values(state);
And then i can concat url with stateValues[0] and stateValues[1];
let linkUrl = "https://domain.pl/ptpdf-gen?selected_posts=" + stateValues[0] + "&advisor=" + stateValues[1];
Works.

Related

axios POST using blob as responseType

So I am trying to download a file via axios and blob. The problem is I need to pass a password, and for that reason I can't use a "GET" request. For test purposes I still made a "GET" request to get me started. Since the project comes to an end I wanted to finally fix that issue but I can't find a solution.
That is my working code with a "GET" request to give you an idea.
axios({
url: `/api/download/?uuid=${uuid}&password=${password}`,
method: "GET",
responseType: "blob",
})
.then((response) => {
var fileURL = window.URL.createObjectURL(
new Blob([response.data])
);
var fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download", filename);
document.body.appendChild(fileLink);
fileLink.click();
self.showLottie = false;
})
.catch(function (error) {
self.showLottie = false;
alert("Download failed");
});
Ok, so basically all I had to do was putting the uuid and password in a params object.
axios({
url: `/api/download`,
method: "GET",
responseType: "blob",
params: {
uuid,
password,
},
})
.then((response) => {
var fileURL = window.URL.createObjectURL(
new Blob([response.data])
);
var fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download", filename);
document.body.appendChild(fileLink);
fileLink.click();
self.showLottie = false;
})
.catch(function () {
self.showLottie = false;
alert("Download failed");
});
Explanation: Are HTTPS URLs encrypted?

How to call http.post using protractor in typescript

I am trying to do http post in protractor. The status of http.post sits in pending status and doesn't return any response.
I am calling a method in onPrepare function under specDone:
jasmine.getEnv().addReporter({
specDone: function(result) {
if (result.status == "failed") {
browser.getCapabilities().then(function(caps) {
var browserName = caps.get("browserName");
browser.takeScreenshot().then(function(png) {
var stream = fs.createWriteStream(
"./reports/screenshots/" +
browserName +
"-" +
result.fullName +
".png"
);
stream.write(new Buffer(png, "base64"));
stream.end();
});
});
}
new PortalData().PushDataToPortal("");
}
});
Below function in called from onPrepare, the API takes the parameter from body. I am using protractor-http-client package for API calls.
export class PortalData {
public PushDataToPortal(result) {
const http: HttpClient = new HttpClient();
const LogFilePathInSharedLocation =
"\\\\10.101.101.11\\temp\\DocStar\\Automation\\TestLogs\\Logs.txt";
http
.post(
someurl,
LogFilePathInSharedLocation,
{ "Content-Type": "application/x-www-form-urlencoded" }
)
.then((response: ResponsePromise) => {
console.log(response);
});
}
Please advise. Thanks!
I would suggest you use Http call in beforeAll instead of onPrepare.
You can try superagent or supertest npm modules:
Example for superagent
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
Example for supertest
const supertest = require('supertest');
const request = supertest(`${baseURL}`);
request.put('/test/sendlocal')
.send(profileAddressData.createData)
.set('Content-Type', 'application/json')
.set('Accept', '*/*')
.expect(200)
.end((err, res) => {
if (err) {
console.error('Error: ', err);
console.error('Response: ', res);
}
});

Add default data to Axios request

I am working on a project with React and a Rails API.
In each of my Axios requests, I want to pass a variable to my API.
Can I configure Axios to tell it to add a variable in the data when I try to POST, DELETE, PUT, PATCH…?
Example:
axios.post('url', { data: 'some_data' }).then(...)
→ API should receive:
data_of_request = { data: 'some_data', added_data_from_config_axios: 'some_variable' }
You can create your own function like this.
const sendPost = (url, data = {}, headers = {}) => {
var body = {...data, added_data_from_config_axios: 'some_variable' };
return axios.post(url, body, { headers });
}
And then, you use this function instead of axios
sendPost(url, { data: 'some_data' }).then(res => {
...
});
Finally I found a better answer.
I just used a built-in function of axios:
const added_data_axios = {
'add_data': '..some_data..'
};
const api = axios.create({
transformRequest: [(data) => {
return {...added_data_axios, ...data};
}, ...axios.defaults.transformRequest],
});

Passport-jwt issue : JWT token is working with postman but not working with UI api call

I have integrated passport-jwt for authentication purpose. It's working like charm but whenever Frontend guy use it from frontend angular 2 its giving Unauthorised 401 . I've tried alot but not getting any clue, it must be a silly mistake though.
my passport strategy file is as
let JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
//let fromHeader = require('passport-jwt').fromHeader
// load up the user model
const User = require('../components/user/model');
const database = require('./database'); // get db config file
const config = require('./config'); // get db config file
module.exports = function(passport) {
//var passportStrategy = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
//opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
console.log("opts.jwtFromRequest==",opts.jwtFromRequest);
opts.secretOrKey = config.secret;//config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
//console.log("opt==",JSON.stringify(opt));
//console.log("jwt_payload===",jwt_payload);
User.findOne({_id: jwt_payload._doc._id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
my route is as
app.get("/api/user/getAll",
passport.authenticate('jwt',{session:false}),
userController.fetchUsers
);
And frontend header append is as follows :
logoutUser(token) {
//const userData = JSON.stringify(userInfo);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', token); //e.g.token = JWT dasddddasdsda
//headers.append('Authentication', token);
console.log(headers)
return this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
.map((response: Response) =〉 {
return response.json()
})
.catch(this.errorHandler);
}
It would really great if anyone can assist me further to identify the mistake.
Second argument for the post method is payload.
so this code below
this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
has to be
this.http.post('http://localhost:9000/api/user/logout', {}, { headers: headers })

How to translate superagent to axios?

I have some upload working for superagent. It involves posting to an api for cloudinary. My question is how do I do the same thing with axios. I'm not sure what superagent.attach and superagent.field relate to in axios.
Basically when I make the post request I need to attach all these fields to the request or else I get bad request and I want to do this in axios not superagent as I am switching over to axios.
Here are all the params:
const image = files[0];
const cloudName = 'tbaustin';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
const timestamp = Date.now()/1000;
const uploadPreset = 'cnh7rzwp';
const paramsStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}ORor-6scjYwQGpNBvMW2HGMkc8k`;
const signature = sha1(paramsStr);
const params = {
'api_key': '177287448318217',
'timestamp': timestamp,
'upload_preset': uploadPreset,
'signature': signature
}
Here is the superagent post request:
let uploadRequest = superagent.post(url)
uploadRequest.attach('file', image);
Object.keys(params).forEach((key) => {
uploadRequest.field(key, params[key]);
});
uploadRequest.end((err, res) => {
if(err) {
alert(err);
return
}
You would need to use FromData as follows:
var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
var fd = new FormData();
fd.append("upload_preset", unsignedUploadPreset);
fd.append("tags", "browser_upload"); // Optional - add tag for image admin in Cloudinary
fd.append("signature", signature);
fd.append("file", file);
const config = {
headers: { "X-Requested-With": "XMLHttpRequest" },
onUploadProgress: function(progressEvent) {
// Do something with the native progress event
}
};
axios.post(url, fd, config)
.then(function (res) {
// File uploaded successfully
console.log(res.data);
})
.catch(function (err) {
console.error('err', err);
});
See full example here