I'm currently using this Contentful-webhook-server to listen for webhooks when content is unpublished.
server.listen(30000, function(){
console.log('Contentful webhook server running on port ' + 30000)
});
server.on('ContentManagement.Entry.publish', function(req){
console.log('An entry was published!', req);
});
server.on('ContentManagement.Entry.unpublish', function(req){
console.log('An entry was unpublished!');
console.log('Deleted SOLR ID: ', req);
});
I'm trying to parse the response I've got but I can't seem to find a way to parse the custom JSON they use in their response. Should I be creating my own server with express or am I missing a way to get the response body in this example code.
The contentful-webhook-server library uses the plain node http module for the server. Thus, the req object is a readable stream that you need to buffer and parse to get the body.
Take a look at https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body for an example.
Related
I am trying to send data to a server (local rest API) from react using post request, if i send an object like this:
{key:"value"}
then i get this at the server:
{ '{"key":"value"}': '' }
It's converting the whole object into key-value pair.
How can i solve this issue?
axios.post('http://localhost:5000/animals', JSON.stringify(data))
.then((response)=>{
console.log(response);
});
If I don't stringify, then I get an empty object at the server, but if I do stringify, then I get this sort of object as mentioned above. Is there any way to convert it back to a normal object?
It looks like the server expects to get data in application/x-www-form-urlencoded encoding, not application/json.
Why?
application/x-www-form-urlencoded encoded data looks like
key1=value1&key2=value2&....
But values are optional, so
key1&key2=value2
works too.
You are sending {"key":"value"} which to the server looks like a key without a value. Since it looks like you have control over the server, change the server implementation to parse the request body as JSON instead. How to do that depends on the framework you are using on the server.
If you are using express.js, use bodyParser.json(). Alternatively send the data application/x-www-form-urlencoded encoded, not as JSON, as suggested by Chinedu.
Performing a POST request with axios
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Can you try constructing the data you want to send as the above exam, send to your api and see if the dummy data comes. No json parse or stringfy needed.
Are you using body-parser middleware in your nodejs express app?
I'm using axios to send a JSON object as a parameter to my api. Before it post request is fired, my data starts of as a JSON object. On the server side, when I console.log(req.params) the data is returned as such
[object Object]
When I used typeof, it returned a string. So then I went to use JSON.parse(). However, when I used that, it returned an error as such
SyntaxError: Unexpected token o in JSON at position 1
I looked for solutions, but nothing I tried seemed to work. Now I'm thinking I'm sending the data to the server incorrectly.
Here's my post request using axios:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/${mediaData}`)
return json;
}
Any thoughts on how I can solve this?
You need to update your code using axios to provide the mediaData in the body of the request instead of the URL:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/`, mediaData)
return json;
}
In the backend (assuming you're using express here), you need to configure your application to use bodyParser:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
And then in your controller update your console.log(req.params) to console.log(req.body); then restart your node server
I am a newcomer to Meteor and am struggling to convert an external service response format as JSON to a 'parseable' format
Code on server side:
if(result){
console.log("fred" + result);
console.log(EJSON.stringify(result, {indent: true}));
var myObj = result;
console.log(myObj.count);
}
The first log statment (server-side) shows that it is an object
The second shows that data has been validly return (via callback)
The third shows undefined as unsuccessful attempt to parse as array.
Then the documentation loses me on how I can query the response for specific elements. Am I forced to parse client side?
I am a newbie with socket.io and have very little exposure to node.js as well
So I started from the simple chat app and built my way up
I can get text messages to be sent from a server to a client when the message comes from another client, like the chat demo app does
But when trying to have the server read a local file and send this contents over using io.emit, what the client side receives seems to be an instance of ArrayBuffer, which in any case confuses the JSON parser
More specifically, server side does
fs.watch('status.json',
function(event, filename){
fs.readFile('status.json',
function(err, data){
if (err) throw err;
io.emit("r2lab status", data);
});
});
and client side does
socket.on('r2lab status', function(json){
console.log("received JSON nodes_info " + json);
var nodes_info = JSON.parse(json);
/* etc.. */
which at run-time triggers this in Console
received JSON nodes_info [object ArrayBuffer]
r2lab.html:1 Uncaught SyntaxError: Unexpected token o
...
As the logic works when I am getting my input by another source than a file, this all strongly suggests that the data I am getting out of readFile is not a plain string but some kind of instance that somehow makes it to the client side; like if I had opened my input file in binary or something.
Could anyone suggest a means to get JSON.parse() to be happy with this scenario ? server-side or client-side, either way would be just fine with me.
Many thanks
You can use Uint8Array view to access that ArrayBuffer and then convert it to string:
socket.on('r2lab status', function(data){
var buffer = new Uint8Array(data)
var fileString= String.fromCharCode.apply(null, buffer)
var obj = JSON.parse(fileString)
});
I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.