Mule 4 : HTTP Requester : How to send multipart/form-data as POST Body for Mule REST Service Call? - multipartform-data

Scenario:
I have to make a REST Service Call from inside Mule 4 and send multipart/form-data as POST Body.
To form the multipart/form data in Dataweave I did the following:
%dw 2.0
output multipart/form-data
---
{
parts: {
Field1: {
headers : {
"Content-Type": "text/plain"
},
content: "Value1"
},
Field2: {
headers : {
"Content-Type": "text/plain"
},
content: "Value2"
},
Field3: {
headers : {
"Content-Type": "text/plain"
},
content: "Value3"
}
}
}
And then in HTTP Request, I set the payload in HTTP Requester Body.
But when I make the REST API Call, I am getting the error Missing Field1
What can be a solution to this?

This worked fine for me:
<ee:transform doc:name="Transform Message">
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output multipart/form-data
---
{
parts: {
Field1: {
headers : {
"Content-Type": "text/plain"
},
content: "Value1"
},
Field2: {
headers : {
"Content-Type": "text/plain"
},
content: "Value2"
},
Field3: {
headers : {
"Content-Type": "text/plain"
},
content: "Value3"
}
}
}]]></ee:set-payload>
</ee:message>
</ee:transform>
<http:request method="POST" doc:name="Request" config-ref="HTTP_Request_configuration" path="/backend" >
</http:request>

Related

Can't read response data and headers in an AngularJS interceptor

I have an API in my server that sends a custom header (lets name it "customHeader") that responds to http://localhost:8081/my/test/api.
I'm trying to read that custom response header from an interceptor in angularJS:
angular.module('oauth.interceptor', []).factory('readResponseHeader', ['$q',
function ($q) {
return {
response': function(response) {
console.log("response: %o", JSON.stringify(response));
console.log("headers: %o", response.headers());
return response;
}
}
}
]);
But all I get are empty data and headers in response. The console log shows the following json as response:
{
"data": [],
"status": 200,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8081/my/test/api",
"data": {
"example": "request data"
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Bearer XXXXXXXXX..."
},
"cached": false
},
"statusText": "OK"
}
And the following as headers:
{
"content-type": "application/json; charset=UTF-8"
}
I expected my customHeader to be there, and be able to read it with something like:
response.headers().customHeader
But it clearly isn't there (in fact, many other headers are missing!).
How am I supposed to read it?
I finally found the problem wasn't really in the AngularJS part, but on the server side part.
The point is that, to be able to access the header, the server must add the Access-Control-Expose-Headers header containing the name of the custom header, something like this:
Access-Control-Expose-Headers: customHeader

How to pass body in post request fetch api call in React Native

My url if opened on browser gives the following error:(attached image)
Body of my api call looks like below :
{
"entityId": 4071,
"listViewId": 0,
"asLookup": false,
"retrieveAllFields": true,
"fullTextSearch": "",
"query": [
],
"pagination": {
"pageNumber": 0,
"recordsCountPerPage": 0
},
"sorting": {
"fieldId": 0,
"direction": 0
}
}
I am calling api in react native using fetch below :
try {
let response = await fetch('url', {
method: 'POST',
headers: {
'tenantid': '1',
'Content-Type': 'application/json',
'language': '0',
},
body: JSON.stringify({
entityId: 4071,
listViewId: 0,
asLookup: false,
retrieveAllFields: true,
fullTextSearch: "",
query: [
],
pagination: {
pageNumber: 0,
recordsCountPerPage: 0
},
sorting: {
fieldId: 0,
direction: 0
}
})
})
let json = await response.json();
console.log("This is response" + json)
this.setState({records: json.results, isFetching:false});
}catch(error){
this.setState({errorMessage:error})
console.log("This is error"+error)
}
This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!
did you use the correct url ?
it should looks like something like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
maybe you should look on the documentations
https://reactnative.dev/docs/network

React js Axios call

I'm fairly to new to React and I can't seem to be able to successfully make a call to an external API using Axios.
The guidelines of the external API are:
Request (in case we know all the parameters)
{
"service": "login",
"username": "john",
"password":"aitis",
"appId": "2001",
"COMPANY": "1000",
"BRANCH": "1000",
"MODULE": "0",
"REFID": "1",
---- optional ---
"LOGINDATE": "2017-12-31 13:59:59",
"TIMEZONEOFFSET": -120
}
Response
{
"success": true,
"clientID": "Wj8Te8EqWghDM......... .....wYGtzlyc1At%2bPrG8t"
}
My code is:
componentDidMount() {
axios.get('http://...serverurl....', {
params: {
service: 'login',
username: 'john',
password: 'aitis',
appID: '2001',
company: '1000',
branch: '1000',
module: '0',
refid: '1'
},
headers: {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
}
})
.then(response => console.log(response));
}
Instead of getting the clientID response I get this:
Response
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
data:
success: false
errorcode: 0
error: "JSON Object must begin with "{" at character 2 of service=login&username=john&password=aitis&appID=2001&Company=1000&Branch=1000&Module=0&Refid=1 JSON Syntax Error : at charact↵
error on character : 2"
__proto__: Object
status: 200
statusText: ""
...
Is something wrong with my call?
Thanks in advance.
If want to send a GET request with those params set those in URL
const URL = `${baseURL}/url?service=login&username=jhon&password=aitis&appID=2001&company=1000&branch=1000&module=0&refid=1`;
axios.get(URL).then(response => console.log(response));
I figured it out. I had to use axios.post instead of axios.get.
Thank you all very much

add data to elastic using angularjs

I am working in a project where to search from firebase data using elastic search and trying to add data to elastic using angularjs but giving error as :
{"data":"","status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],
my code is:
var inputJson =
{
"mappings": {
"carprev": {
"properties": {
"agepolicy33": {
"type": "text"
},
"aircondition33": {
"type": "text"
},
"year33": {
"type": "integer"
}
}
}
}
}
var corsHeaders = {
origin: ["*"],
headers: ['Origin', 'X-Requested-With', { 'Content-Type':
'application/x-www-form-urlencoded' }],
credentials: true,
additionalHeaders: ['access-control-allow-headers', 'Access-Control-
Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With,
Content-Type, CORRELATION_ID'],
additionalExposedHeaders: ['access-control-allow-headers', 'Access-
Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-
Requested-With, Content-Type, CORRELATION_ID']
};
$http({
method: "PUT",
// headers: ['Origin', 'X-Requested-With', 'Content-Type'],
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});
but the same json in inserted into elasticsearch using postman and query data to retrieve from elastic
if anyone can resolve, appreciated
You can try changing the content type to json.
$http({
method: "PUT",
headers: {'Content-Type': 'application/json'},
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});

How do I parse out the file name in a form-data trigger

From Postman I am doing a Post to my Logic App. I am sending the following:
{
"headers": {
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Host": "prod-24.centralus.logic.azure.com:443",
"User-Agent": "PostmanRuntime/6.4.0",
"Postman-Token": "19018057-41ef-4f96-a3a1-cdbf0a1918bc",
"Content-Length": "486",
"Content-Type": "multipart/form-data; boundary=--------------------------117388521639837767242570"
},
"body": {
"$content-type": "multipart/form-data; boundary=--------------------------117388521639837767242570",
"$content": "LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNzM4ODUyMTYzOTgzNzc2NzI0MjU3MA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJzb2Z0d2FyZSI7IGZpbGVuYW1lPSJmaWxlLnppcCINCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vemlwDQoNClBLAwQUAAAACACZVEhLillatwgAAAAGAAAACAAAAGZpbGUudHh0K0ktLslNBQBQSwECHwAUAAAACACZVEhLillatwgAAAAGAAAACAAkAAAAAAAAACAAAAAAAAAAZmlsZS50eHQKACAAAAAAAAEAGADAJqtCS0DTATYTq0JLQNMBlyUeQktA0wFQSwUGAAAAAAEAAQBaAAAALgAAAAAADQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tMTE3Mzg4NTIxNjM5ODM3NzY3MjQyNTcwDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImRldmljZUlkIg0KDQpzMTIzNDUNCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0xMTczODg1MjE2Mzk4Mzc3NjcyNDI1NzAtLQ0K",
"$multipart": [
{
"headers": {
"Content-Disposition": "form-data; name=\"software\"; filename=\"file.zip\"",
"Content-Type": "application/zip"
},
"body": {
"$content-type": "application/zip",
"$content": "UEsDBBQAAAAIAJlUSEuKWVq3CAAAAAYAAAAIAAAAZmlsZS50eHQrSS0uyU0FAFBLAQIfABQAAAAIAJlUSEuKWVq3CAAAAAYAAAAIACQAAAAAAAAAIAAAAAAAAABmaWxlLnR4dAoAIAAAAAAAAQAYAMAmq0JLQNMBNhOrQktA0wGXJR5CS0DTAVBLBQYAAAAAAQABAFoAAAAuAAAAAAA="
}
},
{
"headers": {
"Content-Disposition": "form-data; name=\"deviceId\""
},
"body": {
"$content-type": "application/octet-stream",
"$content": "czEyMzQ1"
}
}
]
}
}
I am trying to get filename value and the content of the file.
I will be creating a Blob file
Thanks,
Here's how I'm doing it. I'm assuming you're using the HTTP trigger set to POST. After the HTTP trigger add a Foreach connector, so you can loop through all the files if you're doing a multi file upload.
The Foreach source will be this expression:
triggerOutputs().body['$multipart']
Within the foreach you can parse the filename with this ugly expression, which is pretty bad but it works:
replace(replace(item().headers['Content-Disposition'], 'form-data; name="myFileUploadInput"; filename="', ''), '"', '')
AFAIK there's no regex support in expressions, which would've been better. You could probably do something with substring, but it'd probably be pretty ugly too.
Here's how you'd get the body within the foreach to save to blob storage: item().body

Resources