Meteor JSON(EJSON) Response parsing difficulties - json

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?

Related

Angular: Observable with subscribe returns error 200 OK as the response is not JSON

I am developing a front-end web application using Angular 11. This application uses several services which return data in JSON format.
I use the async / await javascript constructs and the Observables to get the answers from these services. This is an example my call:
let myResponse = await this.myService(this.myData);
myResponse.subscribe(
res => {
console.log("Res: ",res)
}, (error) => {
console.log("Error: ",error)
}
);
where this.myService contains the code doing the HTTP call using Angular httpClient.
Unfortunately a specific service (only one!) doesn't return data in JSON format but it returns a byte array (string that identifies a pdf -format application/pdf-).
Unfortunately this invocation causes a very strange error with code 200 OK:
How can I do to prevent res from being interpreted as JSON and therefore this error being reported? How can I read resreporting that it will not be in json format?
This service has no errors (with Postman it works perfectly). The problem is Javascript and Observable which are interpreted as JSON. How can I read the content of res in this case?
If a HTTP API call is not returning a JSON, just provide the proper value in the responseType option:
this.httpClient.get('<URL>', {
responseType: 'arraybuffer'
});
Ref: https://angular.io/api/common/http/HttpClient#description

React.js: setState method setting variable to a string instead of object... is there a workaround?

I am trying to fetch a simple JSON element from express.js. I am trying have React assign it to a state variable on the front end. I am using this code to do so:
componentDidMount() {
fetch("/user")
.then(response => response.json())
.then(result => this.setState({myUser:result}))
}
But when I run typeof myUser after this setState command, it says string instead of object. I've tried using JSON.parse(), etc. But either I get an error or it continues to assign the data as a string rather than JSON. What sort of syntax do I need to use in this fetch-then context to coerce the data assignment to be JSON?
I have read this link:
With this code:
componentDidMount(){
fetch('https://abx.com/data/tool.json').then(response =>{
if (!response.ok) throw Error('Response not ok')
return response.json(); // This is built in JSON.parse wrapped as a Promise
}).then(json => {
this.setState({"sections" : json});
}).catch(err =>{
console.log(err);
});
}
But it doesn't solve the problem. I ran this code directly in my application verbatim. When I run typeof on the variable, it says string instead of object. I looked at other posts on Stack Overflow, but I did not see a solution to this.
I figured out what was going wrong (after many hours of experimenting):
On the server side, I was creating a "homegrown" JSON object using string and variable concatenation. I also tried creating the JSON object by doing this:
var str = "name:" + name + ", department:" + department
var user = {str};
Both of these were not working in subtle ways... despite trying different types of gadgetry on the client side, I couldn't get React to interpret the data as a JSON object. But then I had an idea to construct the JSON on the server side (in Express.js) like this:
var user = {};
user["name"] = name;
user["department"] = department;
That immediately cleared things up on the server side and the client side. When using setState() in React, it now sets the value as an object (which was the goal all along).
I think this can be useful to others... if React doesn't seem to understand the JSON, perhaps it is being sent from the server in a subtly incorrect format.

Unable to access data inside a string (i.e. [ object Object ]) that was originally sent as a JSON object

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

Parsing Contentful Webhooks (Custom JSON types)

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.

Transferring a text file's contents over socket.io results in a ArrayBuffer object

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)
});