Sending a csv from front-end to backend using axios - javascript

I am trying to send a csv file from my front end in reactjs to my back end in nodejs using axios. This csv file is selected via a browse UI button and stored in state using react. After searching online this is my code for the HTTPS request:
let formmData = new FormData();
formData.append('file', this.state.selectedFile);
const {data : QueryResult} = await axios({
method: 'post',
url: "https://localhost:...",
formData,
});
Note: this.state.selectedFile contains an object which when logged on console is:
File {name: "MyFile.csv", lastModified: 1614958303483, …}
I also would like to say that this endpoint works fine when using Postman as seen below:
After printing the request in my back-end in the case this request from my frontend I see:
body: {}
I don't understand what I am doing wrong and this passes nothing to my back-end.
I also saw that this was an open issue with axios on GitHub in the past.
Can this be achieved now with axios or should i use another module? Any ideas?

You need to do:
await axios({
method: 'post',
url: "https://localhost:...",
data: formData
});
because when you write just "formData", it becomes : { formData: formData } as per (new ES2015 object shorthand property name).
You can also use:
await axios.post('your_url', formData)

Related

How to send a POST request as form-data when FormData is unavailable? (Airtable scripts)

The Cloudinary API requires to send data using multipart/form-data, but I'm working in an environment where FormData is not available.
How could I do something as simple as this, then?
const formData = new FormData();
formData.append('file', assetUrl);
formData.append('upload_preset', CLOUDINARY_UNSIGNED_UPLOAD_PRESET);
formData.append('cloud_name', CLOUDINARY_CLOUD_NAME);
console.debug(`Uploading file (id: ${id}) to Cloudinary`, CLOUDINARY_UPLOAD_URL, formData);
const response = await fetch(CLOUDINARY_UPLOAD_URL, {
method: 'POST',
body: formData,
});
I tried different approaches, but it seems the Cloudinary API is really sensitive about it, and doesn't allow sending data in any other format other than multipart/form-data.
Cloudinary API supports not only multipart/form-data, but also JSON and application/x-www-form-urlencoded.
If you're sending a string as the value of the file parameter, such as a remote URL (in your case) or Base64, then you can use any of the above-mentioned Content-Types.
For example, you could try the following example which will successfully upload the image into a cloud (you'll want to replace <your-cloud>, <file-url> and <upload-preset> with your actual values):
fetch('https://api.cloudinary.com/v1_1/<your-cloud>/image/upload', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'file': '<file-url>',
'upload_preset': '<upload-preset>'
})
});
Note that the cloud_name is derived from the URL you're sending the data to therefore it should not be sent in your request body.

Sending arrays to PHP server using Node Request?

I'm not sure what I'm doing wrong, however I have an array of data, and I need to send this to a PHP API.
In Postman, I can make this work by going to the Body and selecting form-data. Under my keys, I then make 1 key for every array entry
names[0] = "tom"
names[1] = "harry"
Is there a way to do this using request, or do I have to pass my array through a function and pass it to formData like formData: { 'names[0]': 'tom', 'names[1]': 'harry' } }
What I am currently doing is
const response = await request({
method: 'POST',
url: url,
formData: {names: ["tom", "harry"]}
});
what format of data server accept?
if you want to send as FormData use this code...
if your postman code works, you can generate code for request by postman, below the send button on the right side is link code where you can chose nodejs then request and postman will generate for you request code...
const data = new FormData();
names.forEach((name)=> data.append("names[]", name));
const response = await request({
method: 'POST',
url: url,
formData: data
});

JavaScript Fetch() body not posting correctly

I'm attempting to make a POST request to a URL on my website in JavaScript.
I previously was using jQuery's $.post() function which sends the data object correctly as is, but when attempting to switch to the built-in Fetch() method, I am struggling to send the data in the same form as the jQuery method.
I have the following JavaScript object:
let requestBody = {
username: document.getElementById('username').value,
password: document.getElementById('password').value,
}
and I'm attempting to make a POST request to the URL '/user/login'.
The following jQuery method works:
$.post('/user/login', requestBody);
But when trying with the Fetch method:
fetch(new Request('/user/login'), { method: 'POST', body: requestBody })
I do not see any form body in the Chrome developer tools.
If I try to stringify the requestBody object:
fetch(new Request('/user/login'), { method: 'POST', body: JSON.stringify(requestBody) })
You can see I do not have any data under Form Data as I do with jQuery, and instead it is under Request Payload. The problem with this, is that it is incompatable with my already written backend code.
How can I POST a JavaScript object to a URL with Fetch() just as a jQuery $.post() would?
what you need is to use FormData instead of JSON representation
here is how to do it, basically it looks like this:
var formData = new FormData();
formData.append("username", document.getElementById('username').value);
formData.append("password", document.getElementById('password').value);

Sending FormData not working in React-Native

I tried to communicate with an API to send a picture from an Iphone. I send form data by using Postman (key: mainPicture, value 'the file I choosed') and it's working well.
The problem come when I try to do it in js: the API don't find the file in my request.
Here is my code:
const formData = new FormData();
formData.append('mainPicture', {
uri: mainPicture.uri,
type: 'image/jpg',
name: `${mainPicture.id}.jpg`,
});
// ...
// api come from apisauce package
api.post(API_RES_IMG, formData, { headers: { ['Content-Type']: 'multipart/form-data' } })
Server say: "Error: Multipart: Boundary not found"
Without the content-type the server receive:
{"_parts":{"0":{"0":"mainPicture","1":{"uri":"assets-library://asset/asset.JPG?id=DE830A54-2526-44CB-81FE-00786D152080&ext=JPG","type":"image/jpg","name":"1e23519b-2006-4676-b63c-624e8198e17b.jpg"}}}}
Too much struggle from a simple thing.
Couple of issues I see here:
1) When using the fetch API, we don't need to set the Content-Type header, as fetch will take care of that, plus it will also take care of filling in the boundaries. I am assuming that this is the same with apisauce, however I might be wrong.
2) type: 'image/jpg' is not a valid mime type. It should be type: 'image/jpeg'.
you should add the content type
'Content-Type': type === 'form' ? 'multipart/form-data' : 'application/json',

axios http always returns with empty data

I asked this question before and wasn't able to get an answer. I was able to do use method: 'get' like below to get it working so it was okay but this time I need to use post. In a different project (using react, redux, php, webpack, xampp) the same issue has resurfaced and I am trying to figure it out. So here it is:
register.php
echo $_GET['task'];
index.js
const values = {task: 'doSomething', username: 'username'}
axios({
url: "./server/register.php",
timeout: 20000,
method: 'get',
params: values
}).then(function(response){console.log(response.data)})
When I do the above everything is okay and the data is logged out as 'doSomething'. However, when I try using axios({method: 'POST'}) and changing the php to $_POST['task'] I get an error saying that $_POST['task'] is undefined like below:
index.js
axios({
url: "/projects/myProject/server/register.php",
method: 'post',
data: values
}).then(function(response){console.log(response.data)})
register.php
echo $_POST['task'];
Notice: Undefined index: task
Also when I try this using axios.post() I encounter the exact same problem. I want to use a post request here. Can anyone shed some light on this for me?
Okay after a fair amount of scratching my head I have found an answer. On the PHP this line has to be added before I can access any POST data:
$_POST = json_decode(file_get_contents('php://input'), true);
echo $_POST['task'];
From my understanding the data being inputted from axios is JSON so we must return it in a JSON encoded string using file_get_contents() and then convert this into a php variable from the JSON encoded string using json_decode. Hope this helps someone else. Thank you.
You url has a bad format: it is a path not an url. You have to use either a relative (/register.php) or a absolute (http://localhost/register.php) url depends on how you serve this file with your web server.
As an alternative, on the client side you may massage the data in the JavaScript before POSTing it, eliminating the need to edit the POST data on the server side:
var formatAxiosPostData = function (obj) {
// Create formData object:
var formDataObject = new FormData();
// This step necessary when the obj contains additional overhead data,
// such as what's created on a 'this.$data' Vue.js object:
obj = JSON.parse(JSON.stringify(obj));
// Fill formData object with the key-value pairs:
Object.keys(obj).forEach(function (key) {
formDataObject.append(key, obj[key]);
});
return formDataObject;
};
// example usage:
axios({
url: "/projects/myProject/server/register.php",
method: 'post',
data: formatAxiosPostData(values)
}).then(function (response){
console.log(response.data);
});

Categories