I've just started diving into Node.js after several years of PHP programming and I would like to build a Node.js app for my next project, but I have no clue how to do it.
Are there any resources for a Node.js jumpstart?
Thanks in advance!
You should think of Node.js as some kind of Apache + PHP, meaning that you can program your website and your webserver with Node.
Node has some important differences with your basic PHP, it's evented, asynchronous, non-blocking. You have to learn how to deal with callbacks, don't block the event loop and other things.
What you should do is try to learn the basic stuff with Node at the beginning, here are some great resources: https://stackoverflow.com/tags/node.js/info (my favorite has been nodetuts.com and the excellent book by it's author, Hands on Node).
After you've learned the basics, you can find Express really useful as a web framework and Socket.IO if your app is focused on real-time.
I think you're searching for a node.js jump start to build some meaningful web page with node. Take a look at express, which is a node web framework. They offer a nice but short tutorial (under guide).
You need to run Node.js on a web server. Basically, you need a VPS or Dedicated Server over which you have full control. [PHP runs through the standard web server, Apache. Node.js is the webserver.]
Or you find a Node.js host that'll do it for you.
Node.js is essentially your webserver that would replace Apache so the only hosting that you would find to run Nodejs is a dedicated server or a cloud instance in which you would have to install and run nodejs on. The machine that you run node.js on needs to have a domain name pointed to it or the only way you can access the server is by its IP address which is this case your localhost.
Another option is to use something like Knockout.js (http://knockoutjs.com/), and have the page make JSONP calls to the Node.js server. It's really easy to use Node to send JSON to the client, since it's JavaScript on the server. Using a framework on the client makes it really easy to create a dynamic page based on that JSON data.
The disadvantage is there is no graceful degredation for older browsers. The advantage is a potentially blazing fast website with great AJAX built-in right from the start.
Here is some sample code for using Node to generate a JSONP response:
function writeJsonpResponse(res, jsonpcallback, obj) {
var serialized = JSON.stringify(obj);
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.write(jsonpcallback + '(' + serialized + ');');
res.end();
}
Read the README.
Setup environment.
take a look at package.json (or npm init to create one)
install dependencies (npm install / axios, nodemon, express, mysql, react, babel)
add scripts to start server & webpack if needed
Get acquainted with file structure.
separation of concerns - public/dist, server, db, client
think about the flow of data
Ensure basic HTML structure.
check that bundle.js file / everything it needs is loaded in
need a div id to render react with (like app or root)
Spin up Express server.
Start server and webpack is separate terminals.
check for console.log that server is listening!
Write routes (get and post requests) on your server.
check that get & post requests are working w/ Postman!
Create mySQL database (db/index.js).
Design & import schema (how to structure data tables).
make sure you’re in the db folder when importing yr schema girl!
Connect db to server.
check for console.log that connection is successful!
Write insert/retrieve db query functions.
don’t forget to module.exports those queries to the server!
will call query functions in routes/get & post requests in server
Set up basic React structure.
index.js’s only task is to render your app component to the div id app
need a stateful App component to render all other components
remember to import & export default everything!
Design the rest of your components, decide whether or not they will be functional (stateless) or class components (stateful).
draw it out!
what props (data & functions) do you need to pass down?
Write those components.
Work through one data flow that executes through all the pieces. Get your input handler to send the client side POST request (using axios) to the server route, which will execute your API call (if there is one) and then insert that data to the database.
remember to handle your errors!
Handle events / conditional rendering.
1. user event gives input (onChange e.target.value)
2. write a handleChange f(x) to update state to that new input
3. input is submitted (onClick)
3. write a handleSubmit f(x) that takes in the updated state and makes an axios POST request w/ that { input } to the appropriate server route
remember to bind method functions appropriately!
Call query functions in routes/get & post requests.
Check that data from the client is being stored in the database.
describe those tables my friend!
Do an AJAX get request (use axios or fetch) on client side to api endpoint.
Store the incoming data in setState
May want to do a GET request in componentDidMount to always render appropriate info for client
Yay! You successfully set up your server, database, and client, passed data between them, potentially manipulated the data, stored that data, and displayed the appropriate data to the client!
Tackle those user stories!
Related
I want to use React for a project I am working on, but I also want to use an API.
How can I do it?
I have tried to Google this and ask different people, but I have not got a response yet, so I thought I would ask here. I want to use express and maybe not use create-react-app (as it takes up a lot of storage).
Working on a custom server doesen't preclude the use of an API.
If you want fetch the API from the express server and inject it directly on react frontend you need to enable server side rendering (useful post) and pass the data collected as a props from the server (check this example).
Rather then you can build your react project (using even create-react-app) and build an express server who return the index.html on call.
Personally I prefer the first one solution.
I'm new at Firebase, I'm starting making a project which has to include Firebase and angular2, but I am such confused about how to implement them. I don't know if a there's the need to have a Back-end implementation (like Java or NodeJs) to handle some security issues (like form validation, authentication, routing etc), or it's enough just implementing Angular2 to handle all these issues. I would be so Thankful about any helpful advice how I could implement these both technologies to build my project successfully. Thanks
first firebase is something like your backend firebase can safe get and send request as your backend apps...
and angular js will do the rest like you just said andd all the backend stuff you can handle by firebase :)
This is my simple explanation on how this 2 works together
Always keep in mind that Angular works only in front-end. Its domain is the look and feel, application events, sending data to server and anything else that has something to do with displaying data is coded in this area.
Backend services in the other hand interacts with your database, creating business logic, handling authentications, saving / sending of data and other stuff that interacts with the database is coded from here.
Now how these two interact is done by the frontend service to send HTTP requests to the Server which is the backend service. This is done by using Angulars $http service or the so called jQuery AJAX or the infamous XMLHttpRequest JavaScript native. New technologies today utilizes Web Sockets which is being used by Firebase and some other frameworks, Web Sockets offers a faster way sending / fetching data from server.
The server then interprets the data being sent and send appropriate response. For example getting user list, saving profile, getting reports, logging in, etc.. It would work in this workflow.
1) Angular sends http request to server to get list of users.
2) Backend service installed in the server then interprets the data being sent.
3) Backend service then gets list of users from the database.
4) Backend then sends the data back to the frontend service.
5) Frontend then recieves server response and displays the data to the view.
Also these two is coded separately. To have more detailed explations research about how frontend and backend services interact you can find so much resouces in Google.
I have an application which uses nodejs as server and backbonejs as the frontend framework. As I know, both backbonejs and nodejs handle the url.
I have a question: for example, let say I have page called localhost/project and a page called localhost/details. When I load either of these pages, nodejs server should be called first, and then in the view.jade I have:
script(type="text/javascript", data-main="/js/bootstrap", src="/js/lib/requirejs/require-min.js")
which initiate the control of backbonejs. So, does that mean everytime that I load a NEW page (localhost/details --> localhost/project), I have to reload all the steps for initializing the backbonejs (requireJS work)?
Unless you have to do it differently, perhaps a better approach would be to use node.js as a REST API. I would use a framework like express. Then, in your Backbone code, hook your model and routes up to call your node API and update the views with the data it receives.
Unless you are doing any kind of processing on the server side, you can skip the node step and run your SPA's right off of Firebase or Parse.
I have a small Node.js HTTP server that does requests to a mongo database (with the mongoose module).
What I want to do is query the database, store it in a variable (array) and send it to the client.
Because ideally, when the user clicks on one of the buttons on the html page, the JavaScript will pick-up the event and change the appearance of the website by showing calculations based on data that is stored in the database.
The only way I could come with was just "transferring" the database content to the client browser but if anyone can come with another solution that would be fine too !
So basically my question is :
How can I pass a variable from the Node.js server to the client browser when serving a page ?
Thank you in advance !
If you will be doing more than a couple of these types of transfers, I recommend looking into Socket.IO.
It's a layer that provides quick and easy communication between Node.js servers and web front-ends, by abstracting web sockets when available, and falling back to other transports (such as JSON-P or Flash) when it's not available. Basically, you would call io.emit('something', {yourdata: here}), and it is easily received on the other end. All of the serialization is done for you.
http://socket.io/
Give their demo a shot to see how it works.
I wish to add real time status update notification to a kohanaPHP application with MySQL database i'm developing using node.js, while looking around, i could not find any tutorials about integrating node.js in PHP, i will like to know if its possible and how can it be done and what type of servers should i host the php website on. From what i got its seems node.js does not work on Apache servers. i'll be grateful for help.
Node is it's own server so what you want to do is make a request to the node.js application. You can do this with Curl. One other way is to use Kohana's HMVC feature to make an external request. This example assumes your node.js app returns json.
//Make an external request using post.
$json_request = Request::factory('http://www.example.com/path/to/nodejs')
->method('POST')
->post('my_key', 'value')
->headers('Accept','application/json')
->execute();
//Get the json from the request.
$json_string = $json_request->body();
//Turn the json string into an array.
$json_array = json_decode($json_string);
//Take a look at it with debug.
echo Debug::vars($json_array);
First: You don't run node in any Apache or other web server. It's its own server. So you need to implement data exchange between your Apache/PHP server and node.
You can call your node program via a HTTP request from PHP as soon as something changes and push the new data into your node.
That way you don't need access to MySQL for node, which is not available yet anyway.