POST json file using request module - json

I am planning to translate the curl API call below to node.js though I am still getting an error when doing a POST.
curl -X POST --user user1#customer1:secret http://demo.test.com/controller/actions/38 -F file=#ExportActions.json
Below is initial code using the request - npm module, but the API call still fails.
var requestdata = fs.readFileSync('./ExportActions.json').toString();
var request = require('request');
request.post({
url: 'https://demo.test.com/controller/actions/38',
auth: {
'user': 'user1#customer1',
'pass': 'secret'
},
body: requestdata
}, function(error, response, body){
console.log(body);
});
I am getting the error below every time I run the script:
Could not import Actions: org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
Are there any workarounds when posting a JSON file using the npm request module?
Thanks!

You are trying to upload to file by posting it to the body. It looks like the server wants a multi-part upload instead. This might work better
var req = require('request');
request.post({
url: 'https://demo.test.com/controller/actions/38',
auth: {
'user': 'user1#customer1',
'pass': 'secret'
},
}, function(error, response, body){
console.log(body);
});
var form = req.form()
form.append('file', fs.readFileSync('./ExportActions.json'));

You can use Postman client to check this api instead of curl.

Related

Send POST request in Google Apps Script with Headers and Body

I am trying to send a POST request in order to receive an Access Token in return.
The documentation is as follows:
Client Credentials
This is your first route to obtain an access_token to communicate with the API.
Route : POST https://api.helloasso.com/oauth2/token
Headers
Content-Type = application/x-www-form-urlencoded
Body
client_id = Your Client Id
client_secret = Your Client Secret
grant_type = client_credentials
Solution I tried
Based on this post, I tried the following code:
function qwe()
{
const url = 'https://api.helloasso.com/oauth2/token';
const headers = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method' : 'post',
'contentType': 'application/x-www-form-urlencoded',
'headers': headers
};
const response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response);
Logger.log(data);
}
Upon running this, I get an error "Exception: Request failed for https://api.helloasso.com returned code 400. Truncated server response: {"error":"unauthorized_client","error_description":"client_id is not set"}".
I am a beginner, and would appreciate any help on this! Thank you in advance
Modification points:
In the case of UrlFetchApp, the default content type is application/x-www-form-urlencoded.
From your question and situation, I guessed that your Body might be required to be sent as form data.
If those points are reflected in your script, it becomes as follows.
Modified script:
function qwe() {
const url = 'https://api.helloasso.com/oauth2/token';
const data = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method': 'post',
'payload': data
};
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText())
}
Note:
If you tested this modified script, when an error occurs, please show the detailed error message and provide the official document. By this, I would like to confirm it.
Reference:
fetch(url, params)
Need to make it stringify first
'payload' : JSON.stringify(data)

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

Getting 404 when trying to make POST request from React frontend to Flask backend

I've been working on an app with a React.js frontend and a Python Flask backend (REST API), and one thing I want is for a form to send JSONified data from React to my Flask backend via a POST request, so that it can be processed.
However, I keep getting a 404 (not found) HTTP error, and it's really frustrating because I genuinely don't know how to debug this. I'm not sure what happens in between the request and why this is happening.
Here's the relevant React frontend code:
handleSubmit = (e) => {
e.preventDefault();
const text = {
text : this.state.content
};
const sendText = {
method: 'POST',
headers: { 'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(text)
};
console.log(sendText.body);
const url = 'https://cors-anywhere.herokuapp.com/http://localhost:5000/memes';
fetch(url, sendText).then(response => response.json())
.then(data => console.log(data));
console.log("Success!")
And here's the relevant Flask code
#app.route('/memes', methods=['POST'])
def memes():
data = request.get_json()
text = data["text"]
return jsonify({"result": "success!", "text": text}), 200
Any idea what's wrong? Please feel free to ask any questions about what I'm doing or what I'm using.
Thanks in advance!
Looks like issue with your url
const url = 'https://cors-anywhere.herokuapp.com/http://localhost:5000/memes';
I do not believe that this is a valid url format
maybe you need to use as url:
https://cors-anywhere.herokuapp.com/memes
or
http://localhost:5000/memes

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

How do I access HTTP POST data from meteor?

I have an Iron-router route with which I would like to receive lat/lng data through an HTTP POST request.
This is my attempt:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.params.lat,
'lon' : this.params.lon};
this.response.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
But querying the server with:
curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
Returns {}.
Maybe params doesn't contain post data? I tried to inspect the object and the request but I can't find it.
The connect framework within iron-router uses the bodyParser middleware to parse the data that is sent in the body. The bodyParser makes that data available in the request.body object.
The following works for me:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.request.body.lat,
'lon' : this.request.body.lon};
this.response.writeHead(200, {'Content-Type':
'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
This gives me:
> curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
{"lat":"12","lon":"14"}
Also see here:
http://www.senchalabs.org/connect/bodyParser.html