Generating Access token with axios in react-native - javascript

POSTMAN sample
the same process i want to do it in react-native and i have tried like that
var baseHeaders = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + btoa(client_id + ':' + client_secret)
};
var params = {
client_id: client_id,
client_secret: client_secret,
grant_type: "client_credentials",
}
axios({
method: 'POST',
url: "http://transrv02-ap01.transsyssolutions.com:8080/apex/apxprd/oauth/token",
headers: baseHeaders,
body:params
})
.then((responseJson) => { console.log("clientid---"+responseJson)})
.catch((error) => {
console.error(error);
});
but it have showing 401 error.
Anyone can help me!
thanks in advance....

You can try this...
axios.post('http://transrv02-ap01.transsyssolutions.com:8080/apex/apxprd/oauth/token',
params,
{
headers: baseHeaders
})
.then((responseJson) => { console.log("clientid---"+responseJson)})
.catch((error) => {
console.error(error);
});

Finally I Found My own way not in axios
var baseHeaders = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "Basic " + btoa(client_id + ":" + client_secret)
};
console.log(JSON.stringify(baseHeaders) + "baseHeaders")
var params = "grant_type=client_credentials";
console.log(JSON.stringify(params) + "params")
return fetch('http://apex/apxprd/oauth/token',{
method: "POST",
body: params,
headers: baseHeaders
}).then((response) => response.json()).then((responsetokenJson) => {
console.log(JSON.stringify(responsetokenJson) + "responseJsonclientid")
var token = responsetokenJson.access_token
console.log("this.props.tokens--" + token)
this.setState({
accessToken: token
})
})

Related

'Missing draft message' in Javascript

I am working on this issue from last 3 days. I dived through the stack overflow, but of no use. There are the questions about "Missing draft message", but I am still getting this message. I have tried all the ways they have said. but I am still here.
Here is my code
const str = "My Draft";
const msgBody = btoa(str);
var token = localStorage.getItem("accessToken");
fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/drafts?key=[my api key] HTTP/1.1",
{
method:"post",
ContentType: 'application/json',
Accept: 'application/json',
headers: {
"Authorization": `Bearer ${token}`,
},
message: {
raw: msgBody
}
}
)
.then((data) => data.json())
.then((response) => console.log(response));
please add message in body https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
const str = "My Draft";
const msgBody = btoa(str);
var token = localStorage.getItem("accessToken");
fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/drafts?key=[my api key] HTTP/1.1",
{
method: 'POST',
ContentType: 'application/json',
Accept: 'application/json',
headers: {
"Authorization": `Bearer ${token}`,
},
body: JSON.stringify({ // Here changed
message: {
raw: msgBody
}
}),
}
)
.then((data) => data.json())
.then((response) => console.log(response));

Why is this not working? (fetch()/ getJSON() from WIX)

I have written the following code to access the companies house api (https://developer.company-information.service.gov.uk/). I have googled and tried many things and I have no idea how to get data from this api using fetch/ getJSON. Please help. I am new to javascript.
import { getJSON } from 'wix-fetch';
const baseURL = "https://api.companieshouse.gov.uk"
export function call_companieshouse_api(endpt, search_param){
var api_key = btoa(key)
var url = baseURL + endpt + search_param
getJSON(url, {
method: 'get',
headers: {"Authorization": "Basic " + api_key,
"Content-Type": "application/json",
"Accept": "application/json"},
credentials: "include",
mode: "cors"
})
.then(json => console.log(json.someKey))
.catch(err => console.log(err));
}
I've managed to make it work!
I'm not exactly sure how, but I will explain what I have done (apart from the obvious code change).
I created a new backend file .jsw and in this file is the following code.
import {fetch} from 'wix-fetch';
import btoa from 'btoa'
const baseURL = 'https://api.companieshouse.gov.uk';
var api_key = 'the api key';
export function call_companieshouse_api(endpt, search_param){
var url = baseURL + endpt + search_param;
var base64_key = btoa(api_key)
return fetch(url, {
method: 'GET',
headers: {'Authorization': 'Basic ' + base64_key,
'Content-Type': 'application/json',
'Accept': 'application/json'},
credentials: 'include',
mode: "cors"
}).then(response => response.json());
}
I then have a button click event function with the following code.
export function button1_click(event) {
var search_param = $w('#input1').value;
if (search_param.length <= 1) {
$w('#box1').show();
return;
}
var endpt = "/search/companies?q="
call_companieshouse_api(endpt, search_param)
.then(data => {
console.log(data);
});
}

How to perform ODATA CRUD actions on a SharePoint List using Fetch() instead of AJAX/Axios

I have been looking at documentation on how to perform ODATA CRUD actions on a SharePoint List/Libraries using custom javascript. What I notice is that you need to import jquery to use the axios/ajax calls instead of using the ES6+ Fetch() calls. Does anyone know how to do this and if so, could you provide some examples?
Long story short, I figured it out and wanted to share the code on how I did it for those poor individuals like myself that had 20 tabs open looking for a solution.
Feel free to comment on my choices
GET
// OR YOU CAN USE THE ACTUAL address --> fetch(https://TestSite.sharepoint.us/sites/ExactSite +
fetch(_spPageContextInfo.siteAbsoluteUrl + "/api/web/lists/getbytitle('SharePoint List')/items?$filter=Id eq 1")
.then(res => res.text())
.then(str => new window.DOMParser().parseFromString(str, "application/xml"))
.then(data => {
let itemContent = data.getElementsByTagName("content");
for (i=0; i<1; i++) {
console.log(itemContent[i].childNodes[0]childNodes[1].textContent);
})
POST
You might need to get the RequestDigestValue/X-RequestDigest so I'll include it because I needed it
fetch(_spPageContextInfo.siteAbsoluteUrl + "/_api/contextInfo", {
method: 'POST',
headers: {
'Accept': "application/xml;odata=verbose",
'Content-Type': "application/xml;odata=verbose"
}
})
.then(res => res.text())
.then(str => new window.DOMParser().parseFromString(str, "application/xml"))
.then(res => {
let digValHolder = res.getElementsByTagName("d:FormDigestValue");
let digVal = digValHolder[0].textContent; //This is the value you will need to input in to the Post/Delete Function
addToList(digVal) //This is the function that will do the adding
})
const addToList = (FormDigestValue) => {
let metadata = {
column-name: "value",
__metadata: { type: "SP.Data.SharePoint_x0020_ListListItem" }
}
let postHeader = new Headers({
'X-RequestDigest': FormDigestValue,
'Accept': 'application/json; odata=verbose',
'credentials' : 'include',
'Content-Type': 'application/json; odata=verbose'
});
let postOptions = {
method: 'POST',
headers: postHeader,
credentials: 'include',
body: JSON.stringify(metadata)
}
return fetch(_spPageContextInfo.siteAbsoluteUrl + "/api/web/lists/getbytitle('SharePoint List')/items ", postHeader)
.then(res => console.log(res))
.catch(console.err)
}
DELETE
You will need to include the FormDigest again and I will include it so it will be easier than scrolling up and down on the page
fetch(_spPageContextInfo.siteAbsoluteUrl + "/_api/contextInfo", {
method: 'POST',
headers: {
'Accept': "application/xml;odata=verbose",
'Content-Type': "application/xml;odata=verbose"
}
})
.then(res => res.text())
.then(str => new window.DOMParser().parseFromString(str, "application/xml"))
.then(res => {
let digValHolder = res.getElementsByTagName("d:FormDigestValue");
let digVal = digValHolder[0].textContent; //This is the value you will need to input in to the Post/Delete Function
deleteFromList(digVal) //This is the function that will do the deleting
})
const deleteFromList = (id, FormDigestValue) => {
let deleteHeader = new Headers({
'X-RequestDigest': FormDigestValue,
'Accept': 'application/json; odata=verbose',
'credentials' : 'include',
'Content-Type': 'application/json; odata=verbose',
'IF-MATCH' : '*'
})
let deleteOptions = {
method: 'DELETE',
headers: deleteHeader
}
return fetch(_spPageContextInfo.siteAbsoluteUrl + "/api/web/lists/getbytitle('SharePoint List')/items" + id , deleteHeader )
.then(res => console.log(id + " has been deleted"))
.catch(console.err)
}

How to use an object passed as a function parameter?

I'm setting a CRUD vue app that communicates with an api via axios. I'm having problems trying to set the PATCH function
I use a mixin providing this method
axiosPatch (url, body, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
})
.catch(() => console.log(msg))
}
and I call it somewhere else:
this.axiosPatch('/people/' + this.person.id, { body: { person: { first_name: 'test' } } })
At the api side I this output:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "body"=>{"body"=>{"person"=>{"first_name"=>"test"}}}, "id"=>"712", "person"=>{}}
I expected the output to be
...
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "person"=>{"first_name"=>"test"}, "id"=>"712"}
any help please?
EDIT
approach #1:
this.axiosPatch('/people/' + this.person.id, { person: { first_name: 'test' } })
axiosPatch (url, { body }, msg = 'Failed to update data to server') {
// console.log(body) <-- this outputs 'undefined'
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
}).catch(() => console.log(msg))
}
API output:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "id"=>"712", "person"=>{}}
approach #2:
this.axiosPatch('/people/' + this.person.id, { body: { person: { first_name: 'test' } } })
axiosPatch (url, body, msg = 'Failed to update data to server') {
// console.log(body) <-- this outputs the Object correctly
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body: body.body
}).catch(() => console.log(msg))
}
API output:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "body"=>{"person"=>{"first_name"=>"test"}}, "id"=>"712", "person"=>{}}
The problem is that you are adding an Object with the key body, you can fix it by adding {body} to your param list. This will give you body var with { person: ... }
axiosPatch (url, {body}, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
})
.catch(() => console.log(msg))
}
Also, you can remove the body key in the argument you pass to axiosPatch.
Or you can do you can:
axiosPatch (url, body, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body: body.body
})
.catch(() => console.log(msg))
}
I found a solution:
this.axiosPatch('/people/' + this.person.id, { person: { first_name: 'test' } })
axiosPatch (url, body, msg = 'Failed to update data to server') {
var o = Object.assign({
{ headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
}
},
body
)
return this.$axios.patch(url, o).catch(() => console.log(msg))
}
and I get what I expected.
Is there a better solution?

Wp-login.php not signing in user

let formData = [];
formData.push('log=' + encodeURIComponent(username) + '&pwd=' + encodeURIComponent(password) + '&wp-submit=Log+In&testcookie=1');
await fetch(window.location.origin + '/wp-login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData[0],
}).then((res) => {
console.log(res);
window.location.reload();
}).catch((error) => {
console.error(error);
});
The fetch returns 200 response whenever I post to wp-login.php so I am not sure what is wrong here. Status Code is also 302 whenever there is a successful login but mine is 200.

Categories

Resources