What is Preact exactly? Can I use Node modules? - node.js

I'm still new to the world of Node frameworks. I chose Preact because it seemed to have less dependency than React.
I think I originally misunderstood what exactly this is. I thought it works like PHP: we do tasks on the server page and the client gets the result in HTML form. I understand this is a framework that does not require a Node.js server, but when I create a project using Preact-CLI I can only run it on one Node server (at least opening the generated HTML file does not work by itself, the page does not respond when buttons are pressed, even if I change the file paths from absolute to relative).
I would like to read files in the Preact app, run MySQL queries, but these require Node modules. If const fs = require('fs'); is included in the Preact component, npm start will drop this error:
Module not found: Error: Can't resolve 'fs' in '...'
How do I get Node modules to work, read files, etc.? Should I use AJAX with a separate server (with completely separate code) and communicate with Preact?

Node frameworks => You mean JS Frameworks :)
Preact is a library for the browser, not server, and as such does not have access to the filesystem and other stuff.
To read e.g. from a SQL database, you have to make a call to an API that queries the database and sends the result back to the client (browser).

Preact is a clientside framework like React, it's not a server side rendered framework.
You'll need to make api calls to an external server from your Preact app.

Related

How can I use react with a custom webserver?

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.

How do you do server side processing in a React app?

I'm writing my first Node/React/Express/Next app.
I'm uncertain how to execute server side code when a request comes in.
When there's a request, I need to get some data off the server disk. I'm trying to do this from a javascript file in my pages directory, but the 'fs' module is not accessible from here. I guess that's because the browser must be executing the code (which is confusing for me because I thought next.js meant the server was processing the code and exporting the html back).
I've done much googling about this problem and can't seem to find an answer. Which is bizarre, because this must be one of the most basic requirements of a web app. Maybe the solution is so basic and I'm just overlooking the obvious?
Can anyone provide a brief explanation or pointers in the right direction on how to do server-side processing (eg reading a file from the servers disk) from a /pages/xxx.js file in a React/Express/Next app? Or in other words, how or where do I access the 'fs' module?
The error I get is "ModuleNotFoundError: Module not found: Error: Can't resolve 'fs' in /pages
thanks
Your next.js app is split in two pieces, the part running on the client and server (rendering the pages to HTML) and the part running only on the server (finding the pages and exposing them over HTTP).
What you want to do is possible only on the server and usually done in the realm of express, the routing framework. Next.js is designed to make it easy to create SPAs that do not need a backend but want server-side rendering.
However it does allow modifying the server-only component, if you need to. The documentation for that can be found in the "Custom Server and Routing" section of the docs.
You can then add API routes that the front-end can call to request data form the backend, e.g. by returing JSON that the app can store in the React state.

Importing React component from Node

I would like to do the initial render for my React application on the server side, but am having trouble importing and using React components without using something like babel/register (which is not suitable for production).
I would rather not have to compile my server side code for production, but would like to load an node-suitable React component to send to the client via res.send(React.createElement(Html)).
When I run this I get...
Unexpected token <
I assume this is because my components render method returns <!doctype html>...</html.
Is there a way I can have Node render a React component without having to use babel/compiling code before deploying?
Is there a way I can have Node render a React component without having
to use babel/compiling code before deploying?
No. Since JSX isn't real JavaScript, you need to transpile it at some point, either ahead of time (in a build script) or at run time (using babel-register).
Personally I ignore babel's advice to not use babel-register in production. It works just fine, I always cache + prime responses so performance isn't relevant. I'm open to hearing why transpiling with babel-register is bad though.
Short answer, yes.
this is from the official docs:
ReactDOMServer
The react-dom/server package allows you to render your
components on the server.
ReactDOMServer.renderToString
string renderToString(ReactElement element)
Render a ReactElement to its initial HTML. This should only
be used on the server. React will return an HTML string. You can use
this method to generate HTML on the server and send the markup down on
the initial request for faster page loads and to allow search engines
to crawl your pages for SEO purposes.
If you call ReactDOM.render() on a node that already has this
server-rendered markup, React will preserve it and only attach event
handlers, allowing you to have a very performant first-load
experience.
ReactDOMServer.renderToStaticMarkup
string renderToStaticMarkup(ReactElement element)
Similar to renderToString,
except this doesn't create extra DOM attributes such as data-react-id,
that React uses internally. This is useful if you want to use React as
a simple static page generator, as stripping away the extra attributes
can save lots of bytes.
However, if you want to use JSX you have to use babel, otherwise, you can use Reacts JS Syntax.
Here is a link to an example:
https://github.com/mhart/react-server-example

Does using React.js limits us on using a node.js server

I have been working on React.js for a month now. I have been using Webpack dev server which is a node.js Express server and enables us to render react.js on browser. I want to know whether using React.js will limit us on using only a node.js http server or is there a way we can use a simple http server as well with React.js.
I have also been wondering whether it is useful to use React.js for developing webpages that have mostly pre-fixed contents text fields, data etc. during request/response for any API operation.
Does using React.js limits us on using a node.js server
No. React is predominantly a client side library. It doesn't care how it is served to the client.
In the end you are just writing JavaScript. You can deliver the JavaScript code to the client whichever way you want.
It depends. Generally the answer is no. If you only want to use it as a client-side library, it doesn't matter what the web server is. But actually, react components can also be rendered on server side so you can develop universal/isomorphic apps. In that case you will need a node.js server.
Take a look at this universal example.
we are using php+yii2+react +redux+es6 without node.js server, but ngnix. At the end it is just javascript, so that we use gulp + babelify to translate es6 to es5 and then php yii2 application renders basic container to which react application renders himself.
Node.js is one of the options, you can use wathever server you want, just need something like gulp or webpack to compile your js and all dependencies to the ready to use standalone js.

How to build a website on Node.js?

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!

Resources