I'm struggling with this strange problem, I can't seem to solve. I'm using isomorphic fetch to to post data to a server. I'm sending the body as a JSON-string. But on the server, I can't read the body, it's just an empty object.
The stack is: node, react.
Here is the client-code:
handleSubmit = (event) => {
const { dispatch } = this.props;
fetch('/api/me', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'xxx'
})
})
.then(response => response.json())
.then( json => dispatch( login( json ) ))
.catch( err => console.log(err) )
}
The server code:
var jsonParser = bodyParser.json()
app.post( '/api/me', jsonParser, ( req, res ) => {
console.log('req', req.body);
})
I've tried googling the problem. But the few solutions I found, didn't to the trick.
All help is much appreciated.
BR
Martin
// UPDATE //
figured it out, it was a silly 's', I had forgotten. 'header' should be 'headers'
Thank you for the update that one of the params should be plural:
headers: {
'Accept': ...,
'Content-Type': ...
},
You appended it to the question. Please feel free to accept this as the answer, or to create a new answer with that text, and accept it. Then the "unanswered" queue will contain one less dangling entry for folks to stumble upon.
Related
I have a simple zapier integration built and it works perfectly. However, I'm adding dynamic fields. Again it all seems to work perfectly when I test the zap. My dynamic form fields appear just as I expected.
The problem is sending the value of those dynamic forms to my API. I am using the zapier console and when I configure the API request I am using the following:
Where body['custom_fields'] is supposed to send all my dynamic fields or even all of the fields. But when it hits my API custom_fields parameter is blank.
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: {
'email': bundle.inputData.email,
'custom_fields': bundle.inputData
/**
I've tried the following with no luck:
'custom_fields': bundle.inputData.fields
'custom_fields': bundle.inputData.undefined
'custom_fields': bundle.inputData
*/
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
Ok after a few days, it's the simplest answer.
Obviously an object can't be sent over params.
so instead of having
'custom_fields': bundle.inputData
I just add the whole object to the params and it takes care of all keys and values
params: bundle.inputData
Here is the full body
const options = {
url: 'https://apiendpoint.com',
method: 'POST',
headers: {
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
params: bundle.inputData,
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
You can use the spread operator ...bundle.inputData like explained in the doc:
https://platform.zapier.com/docs/input-designer#how-to-include-dynamic-fields-in-api-calls
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: { ...bundle.inputData }
}
You can even namespace your request data like that:
body: {
request: { ...bundle.inputData }
}
NB : the spread operator raises a syntax error in Zapier code editor, but it works.
I am setting up a Zap for our application in Zapier.
However, I've run into some trouble having the Zap pass over the data in the correct format.
By default it appears Zapier passes the data as json request body, but our backend only accepts form-data.
Is it possible to configure the Zap to send over form-data instead?
In the code below, I've tried to send the data as both params and body, but my backend doesn't any of it as form-data:
const options = {
url: '${URL}',
method: 'POST',
headers: {
'Authorization': ${token},
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
'phone': bundle.inputData.phone,
'email': bundle.inputData.email,
'dialog': bundle.inputData.dialog,
'name': bundle.inputData.name
},
body: {
'name': bundle.inputData.name,
'email': bundle.inputData.email,
'phone': bundle.inputData.phone,
'dialog': bundle.inputData.dialog
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results;
});
Any input is greatly appreciated!
I fixed it by replacing 'Content-Type': 'application/json' with 'Content-Type': 'application/x-www-form-urlencoded'.
I'm working on a project which has rails api as a back-end and angular as a front end. In one particular point I need to make a text/plain call. Even though I set the content-type to 'text/plain', HttpClient tries to parse payload to json. I can't figure out why it behaves like that.
Rails back-end:
def getTranslations
render plain: 'some plain text'
end
Angular Client:
headers = new HttpHeaders({
"Content-Type": "text/plain",
"Accept": "text/plain"
});
this.http.get<any>('http://localhost:3000/getTranslations', { headers: this.headers })
.map((res:Response) => {
console.log(res);
return res.text()
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
)
Response:
"Http failure during parsing for http://localhost:3000/getTranslations"
Unexpected token s in JSON
Thanks.
After looking at angular.io documentation I have found the answer.
Instead of making request by http.get I have changed the method call to
this.http.get('http://localhost:3000/getTranslations', { responseType: 'text'} )
.map((res:string) => {
console.log(res);
return res
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
)
In my current iOS project I need to fetch data from api call with POST method along with login credentials(userName & Password) as authentication header in react native javaScript file.
Can someone Please help me on that.
refernce screen shot
Just set the fetch method to 'POST', add in headers and body as key-value pairs and process response. Here is an example.
var bodyMap = {};
// fill in the body map with keyvalue pair
fetch(POST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': authValue,
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyMap)
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
//process response
})
.catch((error) => {
console.warn(error);
});
I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?