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

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);
});
}

Related

Trustpilot Authentication Error Unknown grant_type

I want to use Trustpilot API to send email review invitation. Before making that call, I need to get an access token. I'm following Trustpilot's documentation in the function below. I keep getting this error of Unknown grant_type. According to the documentation, it is supposed to be set to "password" to get the token and it is not working. I tried this solution but it is not working for me. I can't seem to know what's causing the error especially that it is very general.
trustPilot.getAuthToken = async () => {
let apiKey = process.env.TRUSTPILOT_API
let secrect = process.env.TRUSTPILOT_SECRET
let baseEncoded = Buffer.from(`${apiKey}:${secrect}`).toString('base64')
console.log(baseEncoded, 'base')
let authToken = null
try {
authToken = await axios({
method: 'POST',
url: `https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken`,
headers: { Authorization: 'Basic ' + baseEncoded, 'Content-Type': 'application/x-www-form-urlencoded' },
content: `grant_type=password&username=${process.env.TRUSTPILOT_EMAIL}&password=${process.env.TRUSTPILOT_PASSWORD}`,
})
console.log(authToken, 'auth')
} catch (error) {
console.log(error.response, 'err')
throw { code: '404' }
}
return authToken
}
Please take a look at axios documentation. You are passing content: instead of data:. Axios call should be like this:
authToken = await axios({
method: 'POST',
url: `https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken`,
headers: { Authorization: 'Basic ' + baseEncoded, 'Content-Type': 'application/x-www-form-urlencoded' },
data: `grant_type=password&username=${process.env.TRUSTPILOT_EMAIL}&password=${process.env.TRUSTPILOT_PASSWORD}`,
})

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)
}

Premature end of file error in XML Request

for some reason I am getting this error when trying to create a simple login request to Salesforce.
This works exactly as it should in postman, however, when I try and convert to Google Apps Script it seems to create a "Premature end of file" error.
var myHeaders = {
"Content-Type": 'text/xml',
SOAPAction: '/',
Cookie: "BrowserId=sB-PspOVEeqEttdm-K56tw",
}
/*myHeaders.append("Content-Type", "text/xml");
myHeaders.append("SOAPAction", "\"\"");
myHeaders.append("Cookie", "BrowserId=sB-PspOVEeqEttdm-K56tw");*/
var raw = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Header>\n </Header>\n <Body>\n <login xmlns=\"urn:enterprise.soap.sforce.com\">\n <username>xx#xx.com</username>\n <password>xx</password>\n </login>\n </Body>\n</Envelope>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
muteHttpExceptions : true
};
var response = UrlFetchApp.fetch("https://test.salesforce.com/services/Soap/c/48.0/", requestOptions)
//.then(response => response.text())
//.then(result => logger.log(result))
//.catch(error => logger.log('error', error));
Logger.log(response.getContentText())```
How about this modification?
Modification points:
I think that in this case, Cookie: "BrowserId=sB-PspOVEeqEttdm-K56tw" might not be required.
The properties of body and redirect are not included in the arguments of UrlFetchApp.fetch.
Modified script:
var myHeaders = {
SOAPAction: '/',
}
var raw = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Header>\n </Header>\n <Body>\n <login xmlns=\"urn:enterprise.soap.sforce.com\">\n <username>xx#xx.com</username>\n <password>xx</password>\n </login>\n </Body>\n</Envelope>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
contentType: "text/xml",
payload: raw,
muteHttpExceptions : true
};
var response = UrlFetchApp.fetch("https://test.salesforce.com/services/Soap/c/48.0/", requestOptions);
Logger.log(response.getContentText())
Note:
In this modification, it supposes that the values of SOAPAction, raw and https://test.salesforce.com/services/Soap/c/48.0/ are correct.
Reference:
fetch(url, params)

Axios POST request: Content-type is set, but inside spring it's empty

I'm sending video as POST request using Axios with 'Content-Type': 'multipart/form-data', but inside Spring I see the following error:
"[org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported]"
The Axios code :
async function uploadPost() {
const type = 'video/mp4';
let data = new FormData();
const videoUri = imagePreview;
data =
('video',
{
name: 'mobile-video-upload',
type,
videoUri,
});
axios({
method: 'post',
url: 'http://localhost:8080/post/upload',
body: data,
headers: {
'Content-Type': 'multipart/form-data',
},
}).catch(function(error) {
console.log(error);
});
The function inside Spring :
#CrossOrigin
#ResponseBody
#RequestMapping(value = "/post/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public String create(#RequestParam("file") MultipartFile file) {
Thanks in advance.
Assuming Spring code to be correct, please try with minor changes with Axios.
const axios = require('axios')
const qs = require('querystring')
....... other code .....
const config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(url, qs.stringify(requestBody), config)
.then((result) => {
// Do somthing
})
.catch((err) => {
// Do somthing
})

How can I add raw data body to an axios request?

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.
I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:
axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
{
headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain' }
}).then((response) => {
this.setState({data:response.data});
console.log(this.state.data);
});
Here I added the content type part. But how can I add the body part?
Thank you.
Edit:
Here is a screenshot of the working Postman request
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.
If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.
The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.
The key is to use "Content-Type": "text/plain" as mentioned by #MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
You can pass the params like so
await axios.post(URL, {
key:value //Second param will be your body
},
{
headers: {
Authorization: ``,
'Content-Type': 'application/json'
}
this makes it easier to test/mock in Jest as well
I got same problem. So I looked into the axios document.
I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.
axios.request({
method: 'post',
url: 'http://www.example.com/',
data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
This worked fine for me when trying to send authentication credential in body in raw json format.
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
Used in React js
let url = `${process.env.REACT_APP_API}/validuser`;
let body = JSON.stringify({
loginid: "admin",
password: "admin",
});
var authOptions = {
method: "post",
url: url,
data: body,
headers: {
"Content-Type": "application/json",
},
json: true,
};
axios(authOptions)
.then((resp) => {
console.log("response :- ",resp);
})
.catch((error) => {
alert(error);
});
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
There many methods to send raw data with a post request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
let url='<your domain.extension>';
let data= JSON.stringify('mydata');
axios
.get(url, { data })
.then((res) => {
console.log(res.data);
})
For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.
I hope this works.

Categories

Resources