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
});
Related
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.
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)
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);
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);
});
I am eager to use the new fetch method and I understand it can be used for all http method calls to a Rest endpoint.
So I have the following very simple API endpoint which I know works, get and post requests work. The issue I am having is getting the post request to work on the fetch method.
My code for the fetch method is
var ingredient = {
'name': 'Salt',
}; // a JSON object used as the body for the post request
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
method: "POST",
body: JSON.stringify( ingredient )
})
.then(function(res){ console.log( 'Data posted') })
I then get the following error message. 422 (Unprocessable Entity)
If on the other hand I do something very similar but this time using the classic jQuery ajax post method it works.
$.ajax({
url: 'http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
type: 'POST',
data: 'name=Salt', // or $('#myform').serializeArray()
success: function() { console.log('Data posted'); }
});
Any help here would be appreciated, it feels like I am missing something small here, and documentation on fetch method is scant on the web.
The two request sends two different post bodies one is application/x-www-form-urlencoded (jQuery) and the other is application/json.
You'll have to change the fetch call to send the same type of data as the $.ajax call.
You may have to explicitly set the content type in the fetch request.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var searchParams = new URLSearchParams();
searchParams.append("name", "Salt");
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
method: "POST",
headers: myHeaders,
body: searchParams
})
.then(function(res){ console.log( 'Data posted') })