How to fetch token in a function block - agora.io

i create a working heroku app from here
when i send to
heroku app url/rtc/:channelName/:role/:tokentype/:uid/?expiry=
i get the token fine.
but how to do this in function block?
like the one from here
function fetchToken(uid, channelName, tokenRole) {
return new Promise(function (resolve) {
axios.post('http://<Your Host URL and port>/fetch_rtc_token', {
uid: uid,
channelName: channelName,
role: tokenRole
}, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.then(function (response) {
const token = response.data.token;
resolve(token);
})
.catch(function (error) {
console.log(error);
});
})
}

Related

Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST'

I'm on a page that uses a vue component and one of my patch routes is saying I'm un-authenticated.
<template>
...
<button #click="editPost(attributes.attributes.post_id)"></button>
...
</template>
<script>
export default {
data() {
return {
info: null,
message: null,
postTitle: "",
postContent: ""
}
},
methods: {
editPost(id) { // not working, 401 unauthenticated
console.log('edit post clicked', id);
axios.patch('http://127.0.0.1:8000/api/posts/' + id, {
headers: {
Authorization: 'Bearer 3d58d6cd66e134a59b3a9373a2b4a233e55d00107b9251f654c5c92a2276a1c5'
}
})
.then((response) => {
this.info = response.data;
// this.message = 'Success';
console.log(this.info);
})
.catch((error) => {
console.log(error, error.response.data.message);
this.message = error.response.data.message;
})
},
deletePost(value){
console.log('delete post clicked', value);
}
},
mounted() {
axios.get('http://127.0.0.1:8000/api/posts', { // working as expected, authenticated
headers: {
Authorization: 'Bearer 3d58d6cd66e134a59b3a9373a2b4a233e55d00107b9251f654c5c92a2276a1c5'
}
})
.then((response) => {
this.info = response.data;
this.message = 'Success';
console.log(this.info);
})
.catch((error) => {
console.log(error, error.response.data.message);
this.message = error.response.data.message;
})
}
}
</script>
I dont understand how this can be since I have to authenticate to get the posts on page load and they load fine, with authentication using a Bearer token in header?
Why is the call to axios using a PATCH not working? The PATCH call works in postman fine also.

Axios callback not logging value

I'm making a post request to the Spotify API, and it seems to work fine, but nothing is being returned from the callback. Any ideas?
const spotifyReq = async () => {
try {
await axios.post(
"https://accounts.spotify.com/api/token", "grant_type=client_credentials", {
headers: {
'Authorization': 'Basic' + (Buffer.from(client + ':' + secret, 'base64')),
'Content-Type' : 'application/x-www-form-urlencoded'
},
auth: {
username: "client",
password: "secret"
}
}, (res) => {
console.log(res)
})
} catch (err) {
if (err.request) {
console.log(err.response.data)
} else if (err.response) {
console.log(err.response.data)
} else {
console.log(err)
}
}
}

How to add header to get request in vue js?

I am taking data from api, how to send get request with token after login?
It shows error createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 401
export default new Vuex.Store({
state: {
users: []
},
mutations: {
setUsers(state, args){
state.users = args;
}
},
actions: {
login({ }, arg) {
axios.post('login/', { username: arg.username, password: arg.password })
.then((response) => {
console.log(response);
let accessToken = response.token.data;
localStorage.setItem('token', accessToken);
localStorage.setItem('user', response.data.user);
axios.defaults.headers.common['Authorization'] = accessToken;
window.isSignedIn = true;
router.push('/');
})
.catch((error) => {
console.log(error);
})
},
getUsers({ commit }){
let { data } = axios.get('v1/user/list/');
commit('setUsers', data);
}
}
})
Depends which authentication you are using. Try with:
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
Other HTTP authentication schemes.

Possible Unhandled Promise Rejection / Error: Request failed with status code 400

I know there are some answers on this and I read them all. But none of them helped.
So this is my error message:
And here is my action:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then(response => response.data)
return {
type: "REGISTER_USER",
payload: request,
}
}
Thanks!
Give a try to fetch the library for making API call.
function registerUser(data){
return fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((apiResponse)=>{
console.log("api response", apiResponse)
return {
type: "REGISTER_USER",
api_response: apiResponse.data
}
})
.catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
Invoking the above function
let data = {
email: "youremail#gmail.com,
password:"yourpassword"
}
registerUser(data).then((response)=>{
console.log(response)
})
Log error and succes then check:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
You should use catch handler wherever you call an api with a promise, because you don't when the api will fail and you have to handle the error.
export function registerUser(data){
return axios({
method: 'post',
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers: {
'Content-Type': 'application/json'
}})
.then(function (response) {
//handle success
return {
type: "REGISTER_USER",
payload: response.data,
}
})
.catch(function (err) {
//handle error
return {
type: "REGISTER_USER_FAILED",
payload: null
}
});
}
Call the function like this
const data = {
email: 'asd#asd.asd',
password: 123
}
registerUser(data).then((response)=>{
console.log(response)
})
export function registerUser(data){
return axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then((api_response)=>{
return {
type: "REGISTER_USER",
api_response: api_response.data
}
}).catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
//Invoking the above function
let data = {
email: "youremail#gmail.com,
password:" password"
}
registerUser(data).then((response)=>{
console.log(response)
})

how can we get post data from fetch function in react native to express api?

Question:
How can we get post data from fetch function in react native to express api?
Issue Faced:
I tried the following process but didn't got those variables in back-end API.
How can the variables be achieved in the backend API? Any suggestions are highly appreciated.
Here is the reactive native fetch function:
REACT NATIVE FETCH FUNCTION:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
The express API is given below:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}
Fetch also takes an optional second argument that allows you to
customize the HTTP request. You may want to specify additional
headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will
return a Promise that makes it straightforward to write code that
works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}