Request for an API with Axios - Unauthorized - javascript

I'm trying to make the request for an API, using Axios:
const axios = require ("axios")
const httpsAgent = require('https-agent')
const https = require('https')
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
axios.post("url_api").then(function(response){
console.log(response.data)
}).then(function(response){
console.log(response.data)
}).catch((e)=>{console.log(e)})
but it displays error 401:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string
response: {
status: 401,
statusText: 'Unauthorized',
...
},
data: 'Unauthorized'
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
Is there any more configuration to do? Insomnia/Postman works

The code you've here
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
It's already equivalent to initiating a request, but the problem is you've not passed the url and method parameter which is mandatory
So modify it to
const request = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
method: 'post',
url: 'your_api_url_here', // important change
auth: {
username: 'username'
}
})
Or you can simple follow and do
axios.post('url_here', data );
Finally, your code must look like this
const instance = axios({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
},
method: 'post',
url: 'your_api_url_here',
})
.then(response => console.log(response.data))
.catch((e) => console.log(e));
Choose either one of them but not both.

axios.post("url_api",body,header)

Related

TS/playwright - how to post api request with x-www-form-urlencoded body?

I need to create playwright API request with x-www-form-urlencoded body:
Example from postman:
working postman request example
I was trying to it that way:
async getNewApiAccesToken({request})
{
const postResponse = await request.post("https://login.microsoftonline.com//token",{
ignoreHTTPSErrors: true,
FormData: {
'client_id': 'xyz',
'client_secret': 'xyz',
'grant_type': 'client_credentials',
'scope': 'api://xyz'
}
})
console.log(await postResponse.json());
return postResponse;
But it is not working :/ Could you tell me how can i compose this kind of request in playwright?
Ok, i found a solution!
async getNewApiAccesToken({request})
{
const formData = new URLSearchParams();
formData.append('grant_type', 'client_credentials');
formData.append('client_secret', '8xyz');
formData.append('client_id', 'xyz');
formData.append('scope', 'api://xyz/.default');
const postResponse = await request.post("https://login.microsoftonline.com/9xyz/v2.0/token",{
ignoreHTTPSErrors: true,
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
data: formData.toString()
})
return postResponse;
};

CORS response when sending a DELETE request

I am trying to send a DELETE request to my backend server, but I keep getting this response printed to my console:
Response {type: 'cors', url: 'http://localhost:3003/delete', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3003/delete"
[[Prototype]]: Response
I don't know why this is happening.
server.js
const express = require('express')
const knex = require('knex')
const cors = require('cors')
const db = knex({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'postgres',
password: 'psql',
database: 'blogspot',
port: 5432
}
});
const app = express();
app.use(express.json())
app.use(cors())
// Delete Blog
app.delete('/delete', (req, res) => {
const {id} = req.body;
db.select('*').from('blogs')
.where({
id: id
})
.del()
.then(() => {
res.json('Deleted Successfully')
})
.catch(err => res.status(404).json('An error occured'))
})
fetchAPI.js
function deleteBlog (blog) {
fetch('http://localhost:3003/delete', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(blog)
}).then(resp => {
console.log(resp)
if (resp === 'Deleted Successfully') {
navigate(0)
} else if (resp === 'An error occured') {
console.log('Something went wrong')
} else {
console.log('ERROR')
}
})
}
I keep getting 'ERROR' printed to my console along with the cors response I pasted above. When I refresh, I find that the blog has been deleted, but the response was definitely an error since navigate(0) wasn't run and ERROR was printed to my console. I have tried removing the 'Content-Type': 'application/json' header and sending the id as request params instead but I got the same error.
The fact that the response is of type "cors" just means that some contents are filtered by CORS policy (see https://developer.mozilla.org/en-US/docs/Web/API/Response/type) but you didn't get any error code, the statusCode is 200.
Since your response content type is JSON, you must also resolve the json parsing before reading the response:
function deleteBlog(blog) {
fetch('http://localhost:3003/delete', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(blog)
})
.then(data => data.json())
.then(resp => {
// I also suppose that you will more likely find
// your "Deleted successfully" in the resp.body property, so :
if (resp.body === 'Deleted Successfully') {
navigate(0)
} else if (resp.body === 'An error occured') {
console.log('Something went wrong')
} else {
console.log('ERROR')
}
})
}

How can I close the axios response stream based on some condition at server side?

I want to close the Axios response stream based on some conditions. I am not able to do this by passing the callback
const response = await axios({
method: 'get',
signal,
url: this.url,
httpsAgent: this.agent,
timeout: this.wait_for_connect_ms,
auth: { username: this.username, password: this.password },
responseType: 'stream',
});
response.data.on('data', async (chunks) => {
if(exit) {
// close the stream exit and return
}
});
try unisg Cancel Token
const axios = require('axios');
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const response = await axios({
method: 'get',
signal,
url: this.url,
httpsAgent: this.agent,
timeout: this.wait_for_connect_ms,
auth: { username: this.username, password: this.password },
responseType: 'stream',
cancelToken: source.token
});
then call cancel with your own logic
source.cancel('Kill Request!');

Basic authentication in axios

I've got an problem with basic authentication with axios, i know axios have a dedicated option for this. But it doesn't work in my implementation. I've create an Axios instance, with the auth parameters included, but i still get an 401 (Unauthorized). When i remove the password from the server, the api calls are working.
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true,
auth: {
username: 'username',
password: 'password'
}
});
instance.CancelToken = axios.CancelToken;
instance.isCancel = axios.isCancel;
instance.interceptors.response.use((response) => {
return response;
}, (error) => {
error.response = {
success: false,
message: {
'type': 'error',
'message': i18n.t('sentence.global.error.message')
}
};
return Promise.reject({
...error
});
});
export default instance;
I also tried this:
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true,
},{
auth: {
username: 'username',
password: 'password'
});
}
....
export default instance;
I also tried prefixing the apiurl with username:password#apiurl.com
Thanks in advance!

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