presently I am attempting to make 2 different api calls one after the other within 1 java/nodejs script. It seems after my first function runs successfully, the second one errors with the following:
FetchError: request to failed, reason: socket hang up;
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET'
Below is a code snippet of what I have tried thus far:
const fetch = require("node-fetch");
const formData = require("form-data");
const fs = require("fs");
//const express = require("express");
var apiName = "<LOCAL SYSTEM FILE TO UPLOAD>";
var lookupName = "<LOCAL SYSTEM FILE TO UPLOAD>";
var accessToken = "Bearer <ACCESS TOKEN>";
var url = '<URL API #1>';
var url2 = '<URL API #2>;
var headers = {
'Accept': 'application/json',
'Authorization': accessToken,
};
const form = new formData();
const buffer2 = fs.readFileSync(lookupName);
const buffer = fs.readFileSync(apiName);
const uploadAPI = function uploadAPI() {
form.append("Content-Type", "application/octect-stream");
form.append('file', buffer);
fetch(url, {method: 'POST', headers: headers, body: form})
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
};
const uploadLookup = function uploadLookup() {
form.append("Content-Type", "application/octect-stream");
form.append('file', buffer2);
fetch(url2, {method: 'PUT', headers: headers, body: form})
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
};
if (!apiName !== true) {
uploadAPI()
} else {}
if (!lookupName !== true) {
console.log("Uploading Lookup File");
uploadLookup()
} else {}
I tried using a "setTimeout" function which does not seem to work as I would have liked it to. My best guess is each API call would need to be it's own separate socket connection? Any help with getting me in the right direction is appreciated.
Promise.all([
fetch(url),
fetch(url2)
]).then(function (res) {
// Get a JSON object from each of the responses
return res.json();
}).then(function (data) {
// do something with both sets of data here
console.log(data);
}).catch(function (error) {
// if there's an error, log it
});
Related
I have a code that is supposed to connect to a server, but I am getting a 'Microsoft SharePoint Foundation Error' when I try to run it. What could be causing this error and how can I fix it?
Status 200
OK
`
Microsoft SharePoint Foundation Error.
User: please report details to this Web site's Webmaster.
Webmaster: please see the server's application event log for more details.
`
const adal = require('adal-node');
const clientId = '<myclientID>';
const clientSecret = '<myclientSecret>';
const resource = 'https://<domain>.sharepoint.com/';
const folderName = '';
const context = new adal.AuthenticationContext('https://login.windows.net/common');
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) {
// console.log('Błąd podczas pobierania tokenu dostępu: ' + err);
} else {
upload(tokenResponse.accessToken)
}
});
function upload(accessToken){
const fs = require('fs');
const axios = require('axios');
const filePath = './test.txt';
const sharepointSiteUrl = resource+'teams/<name_my_Sharepoint/';
const fileName = 'test.txt';
const folderName = '';
//add(url='${fileName}',overwrite=true)
const options = {
method: 'POST',
url: sharepointSiteUrl+ "/_api://<myclientID>",
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json;odata=verbose',
'Content-Type': 'application/json;odata=verbose'
},
data: fs.createReadStream(filePath)
};
axios(options)
.then((response) => {
console.log(response.status);
console.log(response.statusText);
console.log(response.data)
})
.catch((error) => {
console.log("test")
console.error(error);
});}
when I'm trying to call the request in front node, I'm getting error in my backend node " RequestError: Error: Invalid URI "undefined"" , it seems like backend node request is not getting the data form my frontend node request.
knowing that uploadLink already have a value and in my browser console the frontend request looks ok
my backend request code
const ThumbnailUpload = async (req, res) => {
const { Uploadlink } = req.body;
const { selectedFile } = req.body;
const clientServerOptions = {
uri: `${Uploadlink}`,
body: JSON.stringify({
name: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': ' application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
}
console.log(Uploadlink);
});
};
and my frontend code is
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append(
'selectedFile',
new Blob([selectedFile], { type: 'image/jpg, image/png, or image/gif' }),
);
formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'image/jpg, image/png, or image/gif',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(response);
});
} catch (error) {
console.log(error);
}
};
any advise ?
change:
const { Uploadlink } = req.body;
to:
const { uploadlink } = req.body;
make variable consistent throughout the code
EDIT
also, since you're uploading a file, you need to use upload middleware before request handler, and file will be within req.file:
route.post('/thumbnail-upload', upload.single('selectedFile'), ThumbnailUpload);
//... handler..
const selectedFile = req.file;
I am attempting to upload a file using the Node example provided in the HubSpot docs.
I am receiving 415(Unsupported media type). The response says I am sending the header application/json even though I am setting multipart/form-data.
const uploadFile = async () => {
const postUrl = `https://api.hubapi.com/filemanager/api/v3/files/upload?hapikey=${HAPI_KEY}`;
const filename = `${APP_ROOT}/src/Files/Deal/4iG_-_CSM_Additional_Capacity/test.txt`;
const headers = {
'Content-Type': 'multipart/form-data'
}
var fileOptions = {
access: 'PUBLIC_INDEXABLE',
overwrite: false,
duplicateValidationStrategy: 'NONE',
duplicateValidationScope: 'ENTIRE_PORTAL'
};
var formData = {
file: fs.createReadStream(filename),
options: JSON.stringify(fileOptions),
folderPath: '/Root'
};
try {
const resp = await axios.post(postUrl, formData, headers); // API request
console.log(resp.data)
} catch (error) {
console.log("Error: ", error);
}
}
Can you see what the problem is or recommend a better way of uploading the file?
Thanks!
The Node example you link to uses the (deprecated) request module, not Axios.
To use Axios (source) you would rewrite that as:
const FormData = require('form-data');
const form = new FormData();
form.append('file', fs.createReadStream(filename));
form.append('options', JSON.stringify(fileOptions));
form.append('folderPath', '/Root');
const config = { headers: form.getHeaders() };
axios.post(postUrl, form, config);
We can Run API in Postman and check NodeJs - Axios Detail in Postman Code Snippet and I Think That's the Better way for this.
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const uploadFile = async () => {
try {
let data = new FormData();
data.append('folderPath', '/Root');
form.append('file', fs.createReadStream(`${APP_ROOT}/src/Files/Deal/4iG_-_CSM_Additional_Capacity/test.txt`));
data.append('options', JSON.stringify({
access: 'PUBLIC_INDEXABLE',
overwrite: false,
duplicateValidationStrategy: 'NONE',
duplicateValidationScope: 'ENTIRE_PORTAL'
}));
var config = {
method: 'post',
url: `https://api.hubapi.com/filemanager/api/v3/files/upload?hapikey=${HAPI_KEY}`,
headers: {
'Content-Type': 'multipart/form-data'
},
data: data
};
const resp = await axios(config); // API request
console.log(resp.data)
} catch (error) {
// error
}
}
When I open my local host, I am getting the following error
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Failed to parse URL from //at getData ((index):60)
Which is pointing to these lines of code
const response = await fetch(url, {
&
getData(`/${url}`)
I'm not sure why I am getting this error when I load the page, as should I only get something like this when I search for something?
This is the larger block of code I am referring to:
document.getElementById('search').addEventListener('submit', function(e) { e.preventDefault(); getData(); })
const form = document.getElementById('Submit')
var formResult = new FormData(form);
const url = '/' + encodeURIComponent(formResult.get("search"));
async function getData(url = '', data = {}) {
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
});
return response.json();
}
getData(`/${url}`)
.then(data => {
console.log(data);
})
Any insight would be appreciated.
Edit based on comments:
Front end:
const form = document.getElementById('Submit')
var formResult = new FormData(form);
const url = '/?url=' + encodeURIComponent(formResult.get("search"));
async function getData(url = '', data = {}) {
const response = await fetch(url) {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
.then(response =>{
console.log(response)
})
.catch(err=>{
console.error(err)
})
Portion of my express Server:
const url = req.body
let urlDecoded = decodeURIComponent(url.url)
console.log(url, urlDecoded)
app.use(express.static("Public"));
app.post('/:url', async function (req, res) {
console.log(req.query.url);
try {
await whoisanalyzer.init();
const site = await whoisanalyzer.open(decodeURIComponent(req.query.url));
const data = await site.analyze();
return res.status(200).json(data);
} catch (ex) {
console.log(ex);
return res.status(500).json({ message : "Oops." });
}});
I think the problem is in the getData() function because of the parameter of it getData(url=' ')
The getData() function replace url with the parameter not with the variable so the fetch url is gonna be
Fetch(" ", { ....})
You have to define the url or the parameter with anther name
You also call the function inside the same function in
getData(`/${url}`)
.then(data => {
console.log(data);
})
That is wrong because the function will never end
You can do it directly like that
document.getElementById('search').addEventListener('submit', async function(e) {
e.preventDefault();
const form = document.getElementById('Submit')
var formResult = new FormData(form);
const url = '/' + encodeURIComponent(formResult.get("search"));
const response = await fetch(url)
.then(response =>{
console.log(response)
})
.catch(err=>{
cosnole.error(err)
})
if you want to take a url and send it to the back end and your front end code is like this
<form action="POST">
<input type="text" name="url">
<input type="submit" value="press">
</form>
so your the code in your js file is gonna be like this below :-
const form = document.querySelector('form')
form.addEventListener('submit', async(e) => {
e.preventDefault()
let urlIN = form.url.value
let url = encodeURIComponent(urlIN)
console.log(url)
const data = await fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: url
})
}).then(data => {
console.log(data)
console.log('get')
})
.catch(err => {
console.error(err)
})
})
and i tested it and it's working , i could send the url of this page and decoded it and i printed it in my console like that
my back end code
const url = req.body
let urlDecoded = decodeURIComponent(url.url)
console.log(url, urlDecoded)
and the result is
{
url: 'https%3A%2F%2Fstackoverflow.com%2Fquestions%2F65757144%2Ferror-when-page-loads-but-before-anything-is-executed%2F65760895%3Fnoredirect%3D1%23comment116273379_65760895'
}
Error when page loads, but before anything is executed
I'm trying to upload an image to slack using the slack api https://api.slack.com/methods/files.upload.
function uploadImage(file) {
var form = new FormData();
form.append('image', file);
var self = this;
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
var token = 'myToken'
axios.post('https://slack.com/api/files.upload?token=' + token, form, config)
.then(function (response) {
console.log(response);
self.imageUploaded("Image uploaded")
})
.catch(function (error) {
console.log(error);
self.error(error);
})
}
I'm getting response with "invalid form data". Any idea what might be going wrong?
Thanks and best regards!
PS: I was able to post an image to slack with python
def post_image(filename, token, channels):
f = {'file': (filename, open(filename, 'rb'))}
response = requests.post(url='https://slack.com/api/files.upload',
data={'token': token, 'channels': channels},
headers={'Accept': 'application/json'},
files=f)
return response.tex
Just need to make the same request with axioms
you can upload a file using axios with the form-data lib
const fs = require("fs");
const axios = require("axios");
const FormData = require("form-data");
const form = new FormData();
form.append("token", 'token here');
form.append("channels", channelId);
form.append("file", fs.createReadStream(__dirname + "/aapl.png"), 'file name');
try {
const res = await axios.post("https://slack.com/api/files.upload", form, {
headers: form.getHeaders(),
});
} catch (err) {
throw new Error(err);
}