Using a CSV file in API POST request in a cypress test - api

I am currently trying to use a CSV file in an api POST request and I am struggling with it! So the error I am getting is a webpack error
Module parse failed: Unexpected token (1:7)
You may need an appropriate loader to handle this file type, currently, no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
What do I need to add or download to accept a CSV file?
Below is the code I am using:
const fileName = require ('file url')
cy.fixture('fileName').then((payload) =>{
cy.request({
url: 'requestUrl',
headers: {
method: 'POST',
'Authorization': 'Bearer access code',
body: payload
}
}).then((res) =>{
cy.log(JSON.stringify(res))
expect(res.status).to.eq(200)
});
});
});

Related

Axios xlsx file download issue

I try to download *.xlsx file in Vue by using Axios get request, however response that i get from GET is not what i expected, what i am trying to do:
on frontend in OnClick method:
const response = await this._fileService.getFileAsBlob(fileName);
const downloadBlob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' })
virtualLink.href = URL.createObjectURL(downloadBlob);
virtualLink.download = file.fileName?? 'file';
virtualLink.click();
next the getFileAsBlob call
public getFileAsBlob(fileName: string): Promise<AxiosResponse<Blob>> {
return this._http.get<Blob>(`API_URL`, {
responseType: 'arraybuffer',
headers: {
"content-type": "application/octet-stream"
}
});
}
Now my concerns:
First, orginal file byte array is: byte[11524]
but in axios response.data this file is ArrayBuffer(15370) (disclaimer here, i've checked respone in backend, everything is working fine, at the last step backend is returning proper byte array)
Second, as i debugged this response, i've noticed, that although i set "content-type": "application/octet-stream" in response i get "application/json, text/plain, */*", what can be cause of it?
As a result, downloaded file is corrupted and cannot be opened by Excel, can somebody point me where am i having a flaw in logic?

Upload a file to an IPFS node from Google Apps Script

I'm trying to upload a file to an IPFS node using Google Apps Script (GAS) without success.
However, I was able to upload a file successfully using Postman. Unfortunately Postman only gives back the source code snippet closest to GAS as a JavaScript - Fetch code, which is not working as is in GAS.
In GAS, the authentication part is working and I know that because if I'm changing the bearer token, then I'm getting invalid credentials error instead of "Invalid request format".
Test code attached where I'm getting the "Invalid request format" error from the server.
For testing purpose, the file which needs to be uploaded, could be created on the fly with the script, but has to be one from Google Drive eventually.
function test() {
let myHeaders = {'Authorization': 'Bearer ...'};
let fileBlob = Utilities.newBlob('Hello!', 'text/plain', 'TestFile.txt');
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
let requestOptions = {
method: 'post',
headers: myHeaders,
papyload: formdata,
muteHttpExceptions: true
};
let url = "https://api.pinata.cloud/pinning/pinFileToIPFS";
let response = UrlFetchApp.fetch(url, requestOptions);
let responeText = JSON.parse(response.getContentText());
Logger.log(responeText);
}
If your access token of Bearer ... is the valid value for using the API, how about the following modification? From the official document, I thought that in the case of your formdata, the values of pinataMetadata and pinataOptions might be required to be the string type.
From:
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
To:
let formdata = {
'file': fileBlob,
'pinataMetadata': JSON.stringify({ 'name': 'TestFileNewName.txt', 'keyvalues': { 'MetaData1': 'Test1', 'MetaData2': 'Test2' } }),
'pinataOptions': JSON.stringify({ 'cidVersion': 0 })
};
And also, please modify papyload: formdata, to payload: formdata,. This has already been mentioned by
TheMaster's comment.
References:
Pin File
fetch(url, params)

Passing JWT in headers with axios

I've created a small project with a node back-end and react front-end to fetch the data through REST calls. I used Axios library, but when I pass the headers with it I keep getting an error saying:
Failed to load resource: the server responded with a status of 401 (Unauthorized).
I found out two methods and both did not work. They are:
export const getUsersDetails=()=>{
console.log('calling');
return (dispatch) => {
return axios.get('http://localhost:3030/users',{headers: { "Authorization": localStorage.getItem('jwtToken') }}).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
and
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.
You need to concatenate 'Bearer ' before the token, like this:
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorage.getItem('jwtToken');

Loading Data from Behance API in React Component

I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --
Fetch API cannot load XXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Not sure how to solve for this.
My code in the Portfolio component below --
getPortfolio = () => {
const USER_ID = `XXX`,
PROJECT_ID = `XXX`,
API_KEY = `XXX`;
const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);
fetch(BEHANCE_URL, {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json();
}).then((responseData) => {
return responseData;
}).catch((err) => {
return err;
});
}
UPDATE: Instead of fetch, using jQuery ajax works. --
$.ajax({
url: BEHANCE_URL,
type: "get",
data: {projects: {}},
dataType: "jsonp"
}).done((response) => {
this.setState({
portfolioData: response['projects']
});
}).fail((error) => {
console.log("Ajax request fails")
console.log(error);
});
This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.
CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.
Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!

Vue Resource Cross-site HTTP request

Normally, when I make a jQuery request to a non-local server, it applies Cross-site HTTP request rules and initially sends an OPTIONS request to verify the existence of an endpoint and then it sends the request, i.e.
GET to domain.tld/api/get/user/data/user_id
jQuery works fine, however I would like to use Vue Resource to deal with requests. In my network log, I see only the actual request being made (no OPTIONS request initially), and no data is being received.
Anybody has an idea how to solve this?
Sample Code:
var options = {
headers: {
'Authorization': 'Bearer xxx'
}
};
this.$http.get(config.api.base_url + 'open/cities',[options])
.then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
jquery-request
Solution:
As #Anton mentioned, it's not necessary to have both requests (environment negligible). Not sure what I have changed to make it work, but the request gave me an error. It consisted in setting the headers correctly. Headers should not be passed as options but as a property of http:
this.$http({
root: config.api.base_url + 'open/cities', // url, endpoint
method: 'GET',
headers: {
'Authorization': 'Bearer xxx'
}
}).then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
Thank you guys, it was a team effort :)
Is it a requirement that an additional OPTIONS request is being made? I have created a small (32 LOC) example which works fine and retrieves the data:
https://jsfiddle.net/ct372m7x/2/
As you can see, the data is being loaded from a non-local server. The example is located on jsfiddle.net and the request is made to httpbin.org - this leads to CORS being applied (you can see the Access-Control-Allow-Origin header in the screenshot below).
What you also see is that only the GET request has been executed, no OPTIONS before that.