This question already has answers here:
AxiosError: getaddrinfo ENOTFOUND
(3 answers)
Closed last month.
I have curl command example. But I wanna make POST request using axios from nodejs. I got this curl example from docs. Here is curl example.
curl -X POST https://example.com/upload
-d "api_key=API_KEY"
-d "#path/filename.mp4"
-H "Content-Type: application/x-www-form-urlencoded"
There is .mp4 in my project dir.
const filePath = __dirname + "/video/Video.mp4";
const fileData = fs.readFileSync(file);
I m used readFileSync to get fileData. Is that actually right? If there is something wrong, please point me out. I hope someone can give me example structure of how to make POST req using axios based on this curl example. Thank youu.
Axios Post Structure:
axios.post(URL, data, config);
const headers = {
"Content-Type": "text/json"
};
const data = {
name: "ABC"
};
const result = await axios.post("https://www.example.com/upload", data, {
headers: headers
});
So in your scenario. try this.
//import these
const Formdata = require('form-data');
const fs = require('fs');
const filePath = __dirname + "/video/Video.mp4";
const fileData = fs.readFileSync(file);
//initialize the form data like this
const dataa = new Formdata();
//now append the form data
dataa.append('file',fileData);
//now for sending the file in the call we use **multipart/form-data**
//let's create headers here
const headerss = {
headers: 'Content-Type': 'multipart/form-data'
}
//All done it's time to post the data to the given URL
axios.post('https://example.com/upload',dataa, headerss).then((res)=> console.log(res));
Related
So I have a package with a function that uploads a file to Twilio:
const FD = require('form-data');
const axios = require('axios');
async function createFunctionResource(serviceUid, functionUid, client){
let collect_file = "Hello World"
let url = `https://serverless-upload.twilio.com/v1/Services/${serviceUid}/Functions/${functionUid}/Versions`
let form = new FD();
collect_file = "test"
form.append("Path", "collect");
form.append("Visibility", "public");
form.append("Content", collect_file, "collect.js");
form.append("contentType", "application/javascript");
await axios.post(url, form, {
headers: {
Authorization: 'Basic ' + Buffer.from(`${client.accountSid}:${client.password}`).toString('base64'),
...form.getHeaders(),
},
})
}
This works completely fine in node.js and it gets uploaded with the message "Hello World" in the file.
I'm trying to put this into an electron app so I preload this package in preload.js with nodeIntegration set to true but whenever I try to upload a file I get:
Request failed with status code 400
With the error response being:
{"message":"No file attached to request","code":70002,"user_error":true,"http_status_code":400,"params":{}}
Does preloading a package make it act exactly the same as it does in node.js?
Can u add cotent-type in headers section and check .
"content-type": "application/json"
Even though you may try and preload a package with axios hoping it runs in a node environment, requests are done under XHR (browser).
To fix this you must specify the adapter to be HTTP by adding adapter: require('axios/lib/adapters/http')
await axios.post(url, form, {
headers: {
Authorization: 'Basic ' + Buffer.from(`${client.accountSid}:${client.password}`).toString('base64'),
...form.getHeaders(),
},
adapter: require('axios/lib/adapters/http'),
})
}
I am trying to upload a local file using NodeJs (the file is in the same directory as app.js) to a remote Laravel server but I'm getting null. For some reason the file doesn't seem to get to the server. I'm not sure what I'm doing wrong..
Here is my node app folder structure
node_app/
├── node_modules/
├── app.js
├── screenshot.jpg
├── package.json
Here is my app.js
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const FormData = require('form-data')
const screenshot = require('screenshot-desktop')
let formData = new FormData()
formData.append('screenshot-file', fs.createReadStream(path.join(__dirname, 'screenshot.jpg')))
axios.post(
`https://www.myapp.com/api/upload-screenshot`,
formData,
{ headers: { 'content-type': 'multipart/form-data' } }
)
And here is my Laravel endpoint
class ScreenshotController extends Controller
{
public function upload(Request $request)
{
// $file is null :(
$file = $request->file('screenshot-file');
$filename = 'screenshot.jpg';
$file->move(storage_path('/uploads/screenshots/'), $filename);
return $filename;
}
}
Error: 'Call to a member function move() on null'
When the request arrives at my Laravel endpoint, there doesn't seem to be a 'screenshot-file' file submitted as it is showing null.
Also using dump($request->all()); it returns an empty array [] which means nothing has been submitted.
However doing a simple post request, it does arrive at the server
axios.post(`https://www.myapp.com/api/upload-screenshot`, {
hello: 'asdf'
})
I finally got it to work after thoroughly reading the documentation for the node.js form-data library. So I will share it with others who might also run into this problem.
I was passing in the wrong headers, I needed to first get the headers from my formData object and then pass them on to axios like this:
function uploadScreenshot()
{
let formData = new FormData()
let stream = fs.createReadStream(path.join(__dirname, 'screenshot.jpg'))
formData.append('screenshot-file', stream)
let formHeaders = formData.getHeaders()
axios.post('https://www.myapp.com/api/upload-screenshot', formData, {
headers: {
...formHeaders,
},
}).catch(error => {
console.log(error)
})
}
I have a client side javascript sdk that submits an image to a server side node.js api that uses the multer library to parse the image.
However ive noticed if i set a header to be content-type multipart-formdata multer will throw an error saying
Error: Multipart: Boundary not found
async submitDocument(id, side, image) {
const url = this.API_URL + "/api/document";
let formData = new FormData();
formData.set("image", image, "front.jpg");
formData.set("side", side);
let headers = new Headers();
headers.set("content-type", "multipart/form-data");
headers.set("Authorization", "Bearer " + this.API_KEY);
const request = {
method: "POST",
body: formData,
headers: headers,
};
try {
const response = await fetch(url, request);
const data = await response.json();
return data;
} catch (err) {
throw err;
}
}
As the error message says, a multipart/form-data content-type requires a boundary parameter.
Don't set the Content-Type yourself. Allow the browser to generate it from the formData object.
npm module connect-multiparty may helpful to you. From server-side node application.
server.js
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
router.post('/api/document', multipartMiddleware);
router.post('/api/document', (req, res) => {
console.log(req.files)
})
post-man api test sample -
https://i.stack.imgur.com/vxBpz.png
I am trying to post a request with my nodejs server to another server and then I have to save response in a file. I am using nodejs https.request module.
This is my request:
var formData = new FormData();
formData.append('first',3);
formData.append('second', '25');
formData.append('source_file', fs.createReadStream(sourcefile));
formData.append('source_image', fs.createReadStream(sourceimage));
var options = {
hostname: 'ip',
path: '/api/path',
method: 'POST'
}
var file = fs.createWriteStream("file.pdf");
var req = https.request(options, (response) => {
response.pipe(file);
console.log("File saved");
response.send("done")
});
req.on('error', (e) => {
console.error(e);
});
req.write(formData);
req.end();
But I am getting the error
First argument must be a string or Buffer
I tried sending my files using formData.toString() but on using this, error disappears but My files are not working and also I have sent data like this:
var formData = new FormData();
formData = {
first: 3,
second: '25',
source_file: fs.createReadStream(sourcefile),
source_image: fs.createReadStream(sourceimage)
};
How can I send my files to other server using this request.
Thanks
I assume you are using form-data.
To fix the First argument must be a string or Buffer error replace:
req.write(formData);
req.end();
with
formData.pipe(req);
(formData behaves like a Node.js ReadableStream)
You should also add headers to your request:
var options = {
hostname: 'ip',
path: '/api/path',
method: 'POST',
headers: formData.getHeaders()
}
Source: https://github.com/form-data/form-data#alternative-submission-methods
I once faced an issue similar to this. I resolved it using the form-data package available on NPM here with the axios package here
the snippet below worked for me
const FormData = require("form-data");
const axios = require("axios");
const form = new FormData();
form.append("first", 3);
// other data should go here
form.append("file", fs.createReadStream("filePath"));
axios({
method: "post",
url: "url",
data: form,
headers: { ...form.getHeaders() }
});
You can use node inbuilt body-parser module to parse the form data into JSON and
you have to use
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
And when you do req.body then it will your form data into an object form.
I have a working Node/Express server and I'm using it to do requests via localhost to an external API. As you can see in my example code, I'm using node-fetch for my basic GET requests.
For every request, I prepare a const url = BASE_URL in advance, needed for the actual external server request.
But I'm getting stuck at my PUT-Request as I can't using node-fetch. So what do I have to do, to notify my Express server with the actual URL for the PUT-Request?
The PUT-Request doesn't work til here.
/* Route: Get Appointment it's availability times */
app.get('/availability/times/:id/:date/:locationId', (req, res) => {
var id = req.params.id;
var date = req.params.date;
var locationId = req.params.locationId;
const url = BASE_URL + '/availability/times?appointmentTypeID=' + id + '&date=' + date + '&calendarID=' + locationId;;
fetch(url, {
mode: "no-cors",
method: "GET",
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'content-type'
},
})
.then(response => response.json())
.then(json => {
res.json(json);
});
});
app.put('/appointments/:id/cancel', (req, res) => {
var id = req.params.id;
const url = BASE_URL + '/appointments/' + id + '/cancel';
res.send(req.body)
});
If you're saying that fetch is undefined in your put request, make sure you are requiring it at the top before any routes var fetch = require('node-fetch'). For your base url, you should store that in a config file. Create a file called config.js that looks something like this:
module.exports = {
'BASE_URL': 'yoururlhere'
}
then require this in your express server var config = require('pathToConfig'); and you can use it by specifying config.BASE_URL
If that doesn't help, please be more specific with what your actual problem is