how can I post a file(please refer my screenshot) with unirest in node.js. I have gone through unirest doc
it's found that can use the below code for sending form-data to a given URL
unirest.post('http://mockbin.com/request')
.headers({'Content-Type': 'multipart/form-data'})
.field('parameter', 'value') // Form field
.attach('file', '/tmp/file') // Attachment
.end(function (response) {
console.log(response.body);
});
please have a look at the screenshot attached. needed to give the key name as 'html'.
how to export the same postman request to node.js(unirest)
In .attach('file', '/tmp/file'), first argument is field name(key name according to you) and second is file path, you can pass as following
var unirest = require('unirest');
unirest.post('http://localhost:3000/api/addProject/')
.headers({'Content-Type': 'multipart/form-data'})
.attach('html', 'D:\\data\\index.html') // Attachment
.end(function (response) {
console.log(response.body);
});
Related
I am making an image upload component in vue js with custom cropping option. The cropped version is being saved in my state as a base64 string. This is it:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6VAAAgAElEQVR4Xu2dCdh+1dT/v3+UDA1KMiQhlCEylDGZSqbI0Jy8JMmYUEloRFIpVJK5EpL0ilJmr6IQKiXzrCKESP2v72vfb8/z/O7hnH2fc/be53z2df2uoj1+9vrd6+y1117r/4kCAQhAAAIQgEDnBP5f5yMyIAQgAAEIQAACQgEjBBCAAAQgAIEEBFDACaAzJAQgAAEIQAAFjAxAAAIQgAAEEhBAASeAzpAQgAAEIAABFDAyAAEIQAACEEhAAAWcADpDQgACEIAABFDAyAAEIAABCEAgAQEUcALoDAkBCEAAAhBAASMDEIAABCAAgQQEUMAJoDMkBCAAAQhAAAWMDEAAAhCAAAQSEEABJ4DOkBCAAAQgAAEUMDIAAQhAAAIQSEAABZwAOkNCAAIQgAAEUMDIAAQgAAEIQCABARRwAugMCQEIQAACEEABIwMQgAAEIACBBARQwAmgMyQEIAABCEAABYwMQAACEIAABBIQQAEngM6QEIAABCAAARQwMgABCEAAAhBIQAAFnAA6Q0IAAhCAAARQwMgABCAAAQhAIAEBFHAC6AwJAQhAAAIQQAEjAxCAAAQgAIEEBFDACaAzJAQgAAEIQAAFjAxAAAIQgAAEEhBAASeAzpAQgAAEIAABFDAyAAEIQAACEEhAAAWcADpDQgACEIAABFDAyAAEIAABCEAgAQEUcALoDAkBCEAAAhBAASMDEIAABCAAgQQEUMAJoDMkBCAAAQhAAA....
now I am trying to send this image to my node js server using post request API. In Postman, I am writing the body selecting "raw" and "json" in this the body in this way:
{
"image" : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6VAAAgAElEQVR4Xu2dCdh+1dT/v3+UDA1KMiQhlCEylDGZSqbI0Jy8JMmYUEloRFIpVJK5EpL0ilJmr6IQKiXzrCKESP2v72vfb8/z/O7hnH2fc/be53z2df2uoj1+9vrd6+y1117r/4kCAQhAAAIQgEDnBP5f5yMyIAQgAAEIQAACQgEjBBCAAAQgAIEEBFDACaAzJAQgAAEIQAAFjAxAAAIQgAAEEhBAASeAzpAQgAAEIAABFDAyAAEIQAACEEhAAAWcADpDQgACEIAABFDAyAAEIAABCEAgAQEUcALoDAkBCEAAAhBAASMDEIAABCAAgQQEUMAJoDMkBCAAAQhAAAWMDEAAAhCAAAQSEEABJ4DOkBCAAAQgAAEUMDIAAQhAAAIQSEAABZwAOkNCAAIQgAAEUMDIAAQgAAEIQCABARRwAugMCQEIQAACEEABIwMQgAAEIACBBARQwAmgMyQEIAABCEAABYwMQAACEIAABBIQQAEngM6QEIAABCAAARQwMgABCEAAAhBIQAAFnAA6Q0IAAhCAAARQwMgABCAAAQhAIAEBFHAC6AwJAQhAAAIQQAEjAxCAAAQgAIEEBFDACaAzJAQgAAEIQAAFjAxAAAIQgAAEEhBAASeAzpAQgAAEIAABFDAyAAEIQAACEEhAAAWcADpDQgACEIAABFDAyAAEIAABCEAgAQEUcALoDAkBCEAAAhBAASMDEIAABCAAgQQEUMAJoDMkBCAAAQhAAAWMDEAAAhCAAAQSEEABJ4DOkBCAAAQgAAEUMDIAAQhAAAIQSEAABZwAOkNCAAIQgAAEUMDIAAQgAAEIQCABARRwAugMCQEIQAACEEABIwMQgAAEIACBBARQwAmgMyQEIAABCEAABYwMQAACEIAABBIQQAEngM6QEIAABCAAARQwMgABCEAAAhBIQAAFnAA6Q0IAAhCAAARQwMgABCAAAQhAIAEBFHAC6AwJAQhAAAIQQAEjAxCA.....
}
The request not detecting this json data in the body and returning error:
{
"image": "\"image\" is required"
}
Also tried the form_data sending method in this way:
var axios = require('axios');
var FormData = require('form-data');
// var fs = require('fs');
var data = new FormData();
data.append('image', formdata.logoFinalImage);
var config = {
method: 'post',
url: myurl,
headers: {
'Authorization': this.state.token,
'Content-Type': 'application/json'
},
data: data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Same issue.
How can I send the final cropped version to the node api endpoint?
Solved the issue. There were two ways of doing it. One is required changes in the backend to configure the code in a way that can receive base64 and convert it to image. Reference: https://medium.com/js-dojo/how-to-upload-base64-images-in-vue-nodejs-4e89635daebc
Other is to make the base64 image file, and then send it to the backend as form-data. Used this one for my case. Reference of this solution: https://gist.github.com/ibreathebsb/a104a9297d5df4c8ae944a4ed149bcf1
if its working in postman then you can create the code from postman itself , select code and search for axios
v8<
if using v8
How to create a post service with formdata?
I sent formdata by Axios.
However, the value of 'req.body.title' on the node-express server is empty.
So now I am sending fetch in the following format.
But I need to upload the file to the server, so I want to send it using formData.
let bodys = 'title=a1&contents=b'
fetch("http://localhost:5000/test", {
method : 'post',
headers : {
'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: bodys
})
.then(function(response){
console.log('Request Succeded ', response);
})
.catch(function (error){
console.log('Failed ', error)
})
I wrote new data using append with new FormData(),
I checked that FormData contains a value on React.
However, the node-express server did not enter the body.
please let me know what to do...
Try sending FormData object instead of raw string as your request body.
const bodys = new FormData();
bodys.append('title', 'a1');
bodys.append('contents', 'b');
This form data will be available in request.body in express.js server.
Edit: to parse the FormData in express.js, you need a middleware like multer
const upload = require('multer');
app.use('/', upload.any(), yourRouteHandler);
You are sending just a string so
You can access your body like below
let bodys = 'title=a1&contents=b'
console.log(req.body); //will print title and contents as you are sending
If you want to access title and contents separately then you have to send data as an object
const bodys = {“title”: “a1”, “contents”: “b”}
console.log(“title”, req.body.title); //will print a1
console.log(“contents”, req.body.contents); //will print b
Chec this thread for more details https://github.com/github/fetch/issues/263
I am using superagent to make a request to Vimeo's Upload API.
My request looks as follows =
var request = require('superagent');
request
.post('https://api.vimeo.com/me/videos')
.set('Authorization', 'bearer ' + myAccessToken)
.set('Accept', 'application/vnd.vimeo.*+json;version=3.2')
.send({ type: "streaming" })
.end(function (error, response) {
//Code
}
I have to use the Accept header here to specify the version as mentioned in their documentation .
My problem is that the response.body is an empty object {}. The response.text is undefined - The response.status is 201.
I should get the response as shown in the documentation. But I get an empty object instead.
If I try the same request through POSTMAN, I get the response that I need. But using superagent I am not able to get it. Is there any additional configuration I need to do to get the response.body?
My client posted data from one website to my website using npm request module.
ie as follows.
testservice : function(req , res){
var data = { title : 'my title' , content : 'my content'};
request.post('https://dev.example.com/test' , data , function(err , response ,body){
if (err) console.log(err);
if(response) console.log('statuscode='+response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method , but i didnt get json data output.
Please help me out to get JSON data which is posted using request post method. Thanks.
Try this:
testservice: function(req, res) {
var data = { title: 'my title', content: 'my content' },
options = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
request.post('https://dev.example.com/test', options, function(err, response, body) {
if (err) console.log(err);
if (response) console.log('statuscode=' + response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method, but i didnt get json data output.
I believe you may be misunderstanding the request.get function. It doesn't "get" the data that was posted to your site, it in fact fires a "get" request off to a particular URL.
If you want to receive data on your site that was POST'ed, then you need to configure your server to listen for POST requests from your friends site and then parse out the posted data from the body of that request.
i.e. in your server code if you're using raw node.js
http.createServer(function(req,res){
if(req.method.toUpperCase() === "POST"){
//code to parse out the data from the post request
}
}).listen(8080)
For more detailed info on parsing out the POST'ed data, see How do you extract POST data in Node.js?
Let me know if this helps, please clarify your question if not.
I am trying to send the content-type in my superagent post request to multipart/form-data.
var myagent = superagent.agent();
myagent
.post('http://localhost/endpoint')
.set('api_key', apikey)
.set('Content-Type', 'multipart/form-data')
.send(fields)
.end(function(error, response){
if(error) {
console.log("Error: " + error);
}
});
The error I get is:
TypeError: Argument must be a string
If I remove the:
.set('Content-Type', 'multipart/form-data')
I don't get any error but my back end is receiving the request as content-type: application/json
How can I force the content type to be multipart/form-data so that I can access req.files()?
First, you do not mention either of the following:
.set('Content-Type', 'multipart/form-data')
OR
.type('form')
Second, you do not use the .send, you use .field(name, value).
Examples
Let's say you wanted to send a form-data request with the following:
two text fields: name and phone
one file: photo
So your request will be something like this:
superagent
.post( 'https://example.com/api/foo.bar' )
.set('Authorization', '...')
.accept('application/json')
.field('name', 'My name')
.field('phone', 'My phone')
.attach('photo', 'path/to/photo.gif')
.then((result) => {
// process the result here
})
.catch((err) => {
throw err;
});
And, let's say you wanted to send JSON as a value of one of your fields, then you'd do this.
try {
await superagent
.post( 'https://example.com/api/dog.crow' )
.accept('application/json')
.field('data', JSON.stringify({ name: 'value' }))
}
catch ( ex ) {
// .catch() stuff
}
// .then() stuff...
Try
.type('form')
instead of
.set('Content-Type', 'multipart/form-data')
See http://visionmedia.github.io/superagent/#setting-the-content-type
It is not clear what is in the fields variable that you are sending, but here is some information that may help you determine where your problem lies.
To begin with, if you are actually trying to build a multi-part request, this is the official documentation for doing so: http://visionmedia.github.com/superagent/#multipart-requests
as for the error that you got...
The reason is that during the process of preparing the request, SuperAgent checks the data to be sent to see if it is a string. If it is not, it attempts to serialize the data based on the value of the 'Content-Type', as seen below:
exports.serialize = {
'application/x-www-form-urlencoded': qs.stringify,
'application/json': JSON.stringify
};
which is used here:
// body
if ('HEAD' != method && !req._headerSent) {
// serialize stuff
if ('string' != typeof data) {
var serialize = exports.serialize[req.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
// content-length
if (data && !req.getHeader('Content-Length')) {
this.set('Content-Length', Buffer.byteLength(data));
}
}
this means that to set a form 'Content-Type' manually you would use
.set('Content-Type', 'application/x-www-form-urlencoded')
or
.type('form') as risyasin mentioned
any other 'Content-Type' will not be serialized, and Buffer.byteLength(data) will subsequently throw the TypeError: Argument must be a string exception if the value of your fields variable is not a string.
Here is what worked for me. I had a single field form, that was uploading a file. I turned the form into a HTML5 FormData element and then did it as follows:
var frm = new FormData(document.getElementById('formId'));
var url = 'url/here';
superagent.post(url)
.attach('fieldInFormName', frm.get('fieldInFormName'))
.end( function (error, response) {
//handle response
});
Please note, I tried various ways of setting the 'Content-Type' manually in superagent, and it never worked correctly because of the multipart identifier needed in the Content-Type.