Node js always Getting error 401 (Unauthorized) - javascript

I'm trying to make POST request on node.js to url, but always get ERROR 401 (Unauthorized).
const response = await fetch('url', {
method: 'POST',
mode: 'no-cors',
headers: {
"Content-Type": "text/html; charset=utf-8",
"Authorization": 'Basic ' + Buffer.from('username' + ":" + "password", 'base64').toString('base64')
},
body: ''
});
I'm tried to use btoa, however node.js does not support that...
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

try this:
let loginData = "username" + ":" + "password";
let encodedData = new Buffer(loginData);
let base64data = encodedData.toString('base64');

Related

Why is axios not returning correctly

I am trying to replace a fetch with axios. I keep getting undefined in my console log.
async componentDidMount() {
console.log('app mounted');
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await axios({
method: 'get',
url: Config.apiUrl + `/api/Orders/GetAllInvoices`,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token }
});
console.log(`axios: ${response.json}`)
this.setState({ invoiceList: response.json });
//const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
// method: "GET",
// headers: headers
//});
//const json = await response.json();
//console.log(json);
//this.setState({ invoiceList: json });
...
... the commented out fetch is working. I just now added the .json even though axios should not need it. Neither way works. What am I doing wrong?
Did you even console.log(response) just to see whats inside of it?
I guess you dont, because response is an object witch has no json key in it. You should use response.data

All requests through one function, which adds accessToken itself

I don't want to repeat headers for all request.
async function fetchA() {
return await axios({
method: 'GET',
url: API_URL + `/api/a`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
}
async function fetchAById(id) {
return await axios({
method: 'GET',
url: API_URL + `/api/a/${id}`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
}
I assigned headers to const but in this case accessToken was null.
What is best way to create function which adds accessToken itself?
function getHeaders() {
const serviceInstance = axios.create({
url: API_URL + `/api/a`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
return serviceInstance;
}
async function fetchA() {
return await getHeaders().get(url)
});
}
I hope this may help.

Sending authorization token with Axios GET does not work

I am making a GET request in my react native app. My code is:
const config = {
headers: {
Authorization: `Bearer ${authToken}`,
},
};
axios.get(url, config);
The authorization token is not being sent along with the request. How do I send it?
You could use the same GET method in two ways.
Method 1
axios.get(your_url, {
headers: {
Authorization: 'Bearer ' + your_token
}
})
Method 2
axios({
method: 'get',
url: your_url,
headers: {
Authorization: 'Bearer ' + your_token
}
})
For POST method
axios({
method: 'post',
url: your_url,
data: { "user_id": 1 }
headers: {
Authorization: 'Bearer ' + your_token
}
})
Please try with the any of above method and let me know.
try this:
var req = {
url: the url ,
method: "get",
headers: {
Authorization: "Bearer " + val,
Accept: "application/json"
}
};
axios(req)
.then(response=>{console.log(response)})
.catch(error => {});
});

jQuery REST PUT request doesn't work in my code?

I just want to make a PUT request with jQuery in Jira.
I've tried it before with SoapUI and there it works, but in my JS file it's not working... It's always giving me an error back (alert with "no" in my case).
Here's my code:
var issueKey = this.JIRA.Issue.getIssueKey();
var username = "admin";
var password = "admin";
var encodedLoginData = btoa(username + ":" + password);
AJS.$.ajax({
type: 'PUT',
contentType: 'application/json',
url: '/jira/rest/api/2/issue/' + issueKey,
dataType: 'json',
async: false,
headers: { 'Authorization': 'Basic ' + encodedLoginData },
data: JSON.stringify('{"update":{"timetracking":[{"edit":{"originalEstimate":"4m","remainingEstimate":"3m"}}]}}'),
success: function(response){ alert("yes"); },
error: function(error){ alert("no"); }
});
As mentioned, the JSON data phrase works in SoapUI, also the login information and the base64 encryption. That's all correct.
But I can't find my fault... Any ideas?
EDIT:
PUT http://localhost:2990/jira/rest/api/2/issue/TEST-3 400
XMLHttpRequest.send # batch.js?devtoolbar=…logged-in=true:5461
send # batch.js?locale=en-US:197
ajax # batch.js?locale=en-US:191
calculate # batch.js?devtoolbar=…logged-in=true:5620
prepareCalculation # batch.js?devtoolbar=…logged-in=true:5620
(anonymous) # batch.js?devtoolbar=…logged-in=true:5620
dispatch # batch.js?locale=en-US:104
h # batch.js?locale=en-US:96
trigger # batch.js?locale=en-US:101
simulate # batch.js?locale=en-US:108
e # batch.js?locale=en-US:114
I think your problem is that the parameter of your JSON.stringify shouldn't be a String. Try to save that into a variable and then make a JSON.stringify of that.
Take into account the result of JSON.stringify. For instance:
JSON.stringify("{}"); //""{}""
JSON.stringify({}); //"{}"
Now your code should be like this For example:
var issueKey = this.JIRA.Issue.getIssueKey();
var username = "admin";
var password = "admin";
var encodedLoginData = btoa(username + ":" + password);
var dataObject = {"update":{"timetracking":[{"edit":{"originalEstimate":"4m","remainingEstimate":"3m"}}]}};
AJS.$.ajax({
type: 'PUT',
contentType: 'application/json',
url: '/jira/rest/api/2/issue/' + issueKey,
dataType: 'json',
async: false,
headers: { 'Authorization': 'Basic ' + encodedLoginData },
data: JSON.stringify(dataObject),
success: function(response){ alert("yes"); },
error: function(error){ alert("no"); }
});
If this is an IIS server, you may need to disable WebDAV, as that grabs all PUT requests.
Happens to be your error is that you're trying to stringify a string
data: JSON.stringify('{update...}')
Nowadays, you don't need jQuery to do HTTP in the browser. All modern browsers come with the Fetch API built in
const issueKey = this.JIRA.Issue.getIssueKey();
const username = "admin";
const password = "admin";
const encodedLoginData = btoa(username + ":" + password);
const body = {
update: {
timetracking: [{
edit: {
originalEstimate: "4m"
remainingEstimate: "3m"
}
}]
}
}
fetch(`/jira/rest/api/2/issue/${issueKey}`, {
method: 'PUT',
body: JSON.stringify(body),
headers: {
'Authorization': 'Basic ' + encodedLoginData
'Content-Type': 'application/json',
},
})
.then(response => alert('yes'))
.catch(error => alert('no'));

Basic authentication with fetch?

I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what's wrong with the code:
let base64 = require('base-64');
let url = 'http://eu.httpbin.org/basic-auth/user/passwd';
let username = 'user';
let password = 'passwd';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {method:'GET',
headers: headers,
//credentials: 'user:passwd'
})
.then(response => response.json())
.then(json => console.log(json));
//.done();
A solution without dependencies.
Node
headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));
Browser
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
You are missing a space between Basic and the encoded username and password.
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
A simple example for copy-pasting into Chrome console:
fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));
or with await:
let response = await fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);
In pure JavaScript you can also use btoa instead of base64.encode():
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
Note that this will only work with ASCII characters.
If you have to handle different encodings, see the linked btoa documentation.
If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:
fetch(url, {
credentials: 'include',
}).then(...);
NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS
npm install base-64 --save
import { encode } from "base-64";
const response = await fetch(URL, {
method: 'post',
headers: new Headers({
'Authorization': 'Basic ' + encode(username + ":" + password),
'Content-Type': 'application/json'
}),
body: JSON.stringify({
"PassengerMobile": "xxxxxxxxxxxx",
"Password": "xxxxxxx"
})
});
const posts = await response.json();
Don't forget to define this whole function as async
get request with authorization for React Native Mobile application, i have spent more time searching for these lines inside fetch
var base64 = require("base-64"); // install it before use from npm i base-64
const uname = "some username goes here";
const pword = "some password goes here";
const getMovies = async () => {
try {
const response = await fetch(
"API URL goes here",
{
headers: {
Authorization: "Basic " + base64.encode(uname + ":" + pword),
},
}
);
data = await response.json();
setData(data);
console.log(data);
// console.log(data.name);
return data;
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
getMovies();
}, []);
// other code
// inside return
<FlatList
keyExtractor={(item) => item.id}
data={data}
renderItem={({ item }) => (
<View style={styles.text_container}>
<Text>{item.name}</Text>
<Text>{item.images[0].name}</Text>
<Text>{item.images[0].src}</Text>
</View>
)}
/>
I'll share a code which has Basic Auth Header form data request body,
let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();
formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
This is not directly related to the initial issue, but probably will help somebody.
I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.
Bad example:
'ABC\username'
Good example:
'ABC\\username'

Categories