Passing Data from Node-Express backend to Vue component - node.js

I'm still learning Vue.js 2 so I do apologize if this question is a bit silly. I'm building an application using MongoDB, Node, Express and Vue. Normally I'd use a template engine such as Ejs where data passed through Express's res.render method can be readily captured in the template.
Is there a similar way to pass data from backend to the root Vue component? For example, normally, a get request fetches some data from Mongodb, express will render the template file and pass data to it.
app.get("/gallery/:id", function(res, req) {
var id = req.params.id;
database.findById(id, function(err, data) {
....
res.render("home", data);
}
});
Now my root Vue application is attached to html file. I'd like to be able to dynamically render the app with data returned from the database.
I've built an app before that streams data from an api and passed it to my Vue component via socket but I feel like using a socket in this case is unnecessary.

Use http. What's the problem? You can use XmlHttp, or a lot of folk seem to be using Axios. Trigger the call in the onload of your page, or use one of the vue lifecycle hooks. The very good vue docs don't have much to say about how and when to do this. We do it in the onload of the page, and we instantiate vue when the request for page data returns.

The question has already been answered, but I wanted to share my approach. I've been experimenting with rendering an object server side using res.render(), putting it in a div where display: none, and then grabbing the object on the client and passing it to Vue's data attribute.

Related

how to do crud operation in react accordian with api call in backend node js using sequelize

I have 5 Accordions in localhost:3000/management page and each having dynamic values fetching API in backend node Js using Sequelize so how can I show the 5 accordions value in node js????
I want to know for 5 accordion how can I define backend code for one react URL in frontend???
On your backend your route should start a function that will return the correct value from your db using Sequelize. I don't know if you're using Express, Fastify etc and you didn't provide code so I won't be able to provide a more detailed explanation but feel free to update your post
On your React frontend you need to fetch from your backend. So that would be something like
const data = await fetch("https://yourapiadress...").json()
Once you have this you can easily use it in your accordion
data.map(content =>{
return <Accordion>{content}</Accordion>
})

How can i write a function to call(POST) an API, from within the web server and not the browser. -NextJS

How can i write a function to call an API, from web server to API within the server itself.
I do not want the browser to know that he is calling an API or and information about the API, even the link.
The API call(POST method) should be executed on the server.
Using Nextjs with axios.
I also want the function to be a component.
If you want to fetch data before loading the page (when the actural page load request happens), use server side rendering.
In Next.js you can use getServerSideProps for doing this. By doing this, you get to keep the api call inside the component, and the sever will fetch the data before rendering your component. Attaching a sample of code that you can refer for this.
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
For more info, please visit the nextjs official documents. Attaching a link for the above example.
https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.
Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.
Most of this question will be pseudo code since I haven't started with the Node portion yet.
The idea is that from within the React component it would call the Node app who in turn would call the external API.
React -> Node -> External API
So the React component would be something like so:
handleSubmit: function() {
var data = this.refs.testData.getDomNode().value;
$.ajax({
url: '/my-node-endpoint',
dataType: 'json',
type: 'POST',
data: { test: data },
success: function(data) {
// Whatever success call I want to make
}.bind(this)
})
}
And then in my Node app it would like something like this:
app.post('/my-node-endpoint', function(req, res) {
// Store the values we are posting as JSON
// Start the post request
// On End tell the React component everything is ok
// Prosper
});
As always, thanks for any help that is offered.
Your thought process looks right to me.
If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.
Several improvements to your code:
As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

Render EJS and save it to Redis

In my Node-Express app I'm using Postgre as main data and Redis as cache system.
When a visitor request an url, my app request the json to Redis. If isn't available, make a request to Postgre, save the json to Redis and then render the EJS template. The next request to the same url, I get the json from Redis and render the template.
Now I want to save to Redis the full rendered template instead of json to save CPU usage. I tried this trick but it did not work:
Render ejs file in node.js
Any ideas or suggestions how to do it ??
Thanks in advance for your help.
The Express API reference shows that res.render() accepts a callback as the last argument. That callback is called with (err, html), so just pass in a callback and store the (string) html into redis.

Node.js works with CouchDB and Backbone.js, How json is being served?

I am trying to build a test app for learning Node.js. I came from wordpress background and Apache has setup most of backend logics for me. But now, I have to build my own. I have a question about how to serve JSON files from server side to client side. What is the workflow -- Backbone.js handle all client side Data manipulation, send/save/get/fetch from couchDB, serve JSON object from NODE.js backend?
I am using Express Microframework for building HTTP server, installed the Cradle middleware for access CouchDB NoSQL database. I successfully posted the data from Client side HTML (Jade template engine) to the CouchDB Database/Document and able to retrieve those data back from Server through Cradle middleware. Things work out great. But it was all done by Backend.
I want to use Backbone.js for my client side Javascript. Backbone.js is looking for JSON object which send back from the HTTP server. Cradle Middleware is able to create JSON object but only send them directly to the Jade Template, I could use Jade syntax for loop to iterate over the data object but it still not meet what I want for Backbone.js handle all the data entry. I realize that I need to get JSON obj via ajax ( either a file generated by HTTP then send back to the client OR send straight object to the client ). Cradle Middleware could not do that.
I did more research on this questions. I tried CouchApp, it does what I need. Using the Backbone.js to handling all the data, send/save/fetch data from CouchDB database. But it is a running in CouchApp, it is not an Express Node.js workflow. ( Maybe I am wrong or just do not how it work )
I tried backbone-couchdb.js. I read through the Details and still do not know it is going to help me to get what I want. ( Maybe need more tutorial or code example ). I am still thinking that I need a Backbone CouchDB driver to connect those two and somehow serving them by NODE.js backend.
Is there anybody who could tell me about how JSON file is being served by Node.js, how backbone.js interact with data save/fetch/get from CouchDB? What is the best practice / workflow? Other good resources, code examples, useful tools?
Cradle Middleware is able to create JSON object but only send them directly to the Jade Template
This is incorrect. You can just send the json back without rendering a template.
function(req, res, next){
db.view('user/byUsername', { key: 'luke' }, function (err, doc) {
res.send(doc); // or res.json(doc);
});
}

Resources