I'm using SSR with react and i18next. I don't have a lot experience with Node.js, so the question is:
Is it a normal way to make an external http request in a start of a server script execution and pass all the left server script code into the then function of a returned Promise instance as a later continuation part of the script.
Server code which is bundled and then is started
server.js
import express from 'express';
import promiseRequest from 'request-promise';
import i18next from "i18next";
import middleware from "i18next-express-middleware";
import render from './render';
const app = express();
promiseRequest.get('https://api/localization')
.then(data => {
i18next.use(middleware.LanguageDetector);
i18next.init();
app.use(middleware.handle(i18next));
app.listen(3000, () =>
console.log('App is running')
);
return app;
});
The reason I go this way is because I need to init i18n based on a response from a server.
Why do you need to make an api request to figure out your localization needs? Wouldn't that be a part of the incoming request to your static server (gimme the website in english, french, etc)? I'm unclear about your use case. Are you trying to have several instances of your static server to serve different languages?
A common model I've seen is to have multiple static files pre-generated, per localization, and then serve them up based on the request, ex: have a route that returns the english version when the user makes a request to http://yourwebsite.com/en, the french one at http://yourwebsite.com/fr or http://yourwebsite.fr, etc.
Related
I am (very) new to node.js and I am trying to get a development environment started with React.
const express = require('express')
const mongoose = require('mongoose')
const app = express()
// this displays the index.html file
app.use(express.static(__dirname + '/public'));
// trying to see the app.js
app.get('/', (req, res) => {
res.render('app')
})
app.listen(process.env.PORT || 5000);
Right now I am simply trying to be able to view my app.js when I run nodemon. But right now it is only showing the index.html file in the public folder. and when I run npm start it renders both the index.html and the app.js.
I am 100% doing something wrong and am not in my element here. Any help/advice would be appreciated.
My full repo is here for viewing here
Thank you in advance.
Your code is simply serving a static HTML file located in the public directory everytime the user make a GET request to the root (in your case, localhost:5000). It is not interacting with React yet.
Usually when starting a project with React (frontend) and Node (backend), you would create them as separate projects, in separate repositories.
So you could create a React application using a bootstrap such as create-react-app running on PORT 3000 and in another terminal tab, start your NodeJS application in PORT 5000 like in your example. Then, you can call your backend endpoint from your frontend React application, by referencing http://localhost:5000
By doing this, your backend code don't need to serve static files anymore, it can return data such as JSON and make connections to a database for example.
Since your question is not specific enough, you could be talking about server side render. In server side render apps using Node and React, you have a frontend built with React and a Node server that will return the same React code as a string, using the react-dom/server package to help. This is more complex, but basically you will have the same React code on the client AND on the server. There are performance benefits, because the user can see some content rendered right when he enters the page, without having to wait the React bundle (javascript file) to load. If you want to know more about creating a server side render app with React and Node, there is a nice digital ocean tutorial here
If you want to connect your react js project to the node js
In Development
you simply run their server and start it
In Production
You can use sendFile function coming from express.js to run the frontend
https://dev.to/loujaybee/using-create-react-app-with-express
I recently started learning JS and I am a basic programming background previously but always stuck on OOPs concepts.
So here we are importing I think the express module by writing the required (express). But I don't understand why we are storing this in a variable.
Likewise then storing express() in app variable then using app variable to do some stuff.
I mean how's this is working? What is What in this code block? Please explain in detail.
Thanks in advance.
const express = require('express')
const { createReadStream } = require('fs')
const app = express()
app.get('/' , (req,res) => {
createReadStream('index.html').pipe(res)
})
Line 1: You import the express node module that you installed with npm i express and store it in a constant (const).
Line 2: You import the function or variable createReadStream from the file system module of node.js (fs module) and make it available for use in this file.
Line 3 you assign the express() function from the express module above to a constant called app, so you now have everything express related available to you on the app constant.
Line 4-5: You use the get method from the express() function you have stored in the app constant, and create a route for the base url of your app / (e.g. domain.com/ or localhost:8000/). If you request something from the server you send a GET request. If you send some data use POST or PUT, for example, the express() function in app have these methods for you to use, too (app.post for example).
When Postman or a regular user with a browser hits this part of your domain (route) with a GET request, the arrow function on line 4 (req, res) => kicks in. It takes in the request (req) and the result (res) parameters so you can use those inside of the function if you wish. On the req parameter you have available whatever is in the body the user sends in from a form, for example. In your case your route streams back a html file to the user via http in order to display it in the user's browser.
I'm working on a MEEN-stack (MySQL, EmberJS, Express, and NodeJS) project. I have never worked with Ember at all. My only front-end experience is jQuery.
The project is separated into folders, with the front-end (Ember) in one folder and the Express API in another. Front-end will handling loading in web-pages while sending requests to Express API for database requests / authentication / more.
I am currently able to connect the two servers via an explicit URL with jQuery's Ajax method in a webpage's static javascript file (along with allowing CORS and modifying the Ember environment file in app/config).
My confusion is that there is definitely a more elegant solution for connecting the two, but I'm lost on how to go about it.
From looking at tutorials, I have attempted adding an application.js file in the Ember Front-End app/adapters folder:
import DS from "ember-data";
export default DS.RESTAdapter.extend({
host: 'http://localhost:9029',
namespace: 'api'
});
But I don't have the knowledge to fully implement it or test it. What am I missing? How do I take advantage of the adapter file?
When you start ember use:
ember server --proxy 'http://localhost:9029'
Assuming that you node server is serving your api from http://localhost:9029 as you start the ember server with the proxy the ember-cli will spin up a very simple node proxy that will proxy your requests while you are developing.
Then you can remove the host from your adapter.js file
import DS from "ember-data";
export default DS.RESTAdapter.extend({
namespace: 'api'
});
Also if you want brevity:
ember s -pxy 'http://<YOUR LOCAL SERVER AND PORT>'
I'm super new to server-side, so apologies for such a basic question.
I was looking at an example of a Node/Express server file in this blog post and came across this:
var http = require('http')
What is the purpose of requiring 'http'? It doesn't seem to be any kind of dependency. Is this something from Express/Node? Could someone please explain?
'http' is a core module in node.js.
Node.js needs to create http/https servers, hence we have to import the http module in order to create an HTTP Server.
Thus,
var http = require('http')
is just to import the built-in http module, so that we can create http server which will respond to our requests. After importing the module, a server can be created by using the createServer() method offered by http module.
var server = http.createServer(handleRequest);
For more detailed info, visit https://nodejs.org/api/http.html
You’ll use Node’s require function to use the http module. require is similar to keywords like import or include in other languages. require takes the name of a package as a string argument and returns a package. There’s nothing special about the object that’s returned—it’s often an object, but it could be a function or a string or a number.
var http = require('http')
Node has a built-in module called http. It is useful for building web applications. and by using the above code you are getting all things those are exposed by http module.
It's like creating object of a class and getting access of all the properties(Variable and Functions)of that class.
To use the HTTP server and client one must require('http').
It is an API provided by Node.js. If you want to know more on this, https://nodejs.org/api/http.html
It doesn't seem to be any kind of dependency
But it is. Further down in the example there's this line:
var server = http.createServer(app).listen(port, function() { ...
which requires http to work. You probably missed it.
I am creating a live streaming application using meteor. Currently I have a need to create a live transcoding option, so I am trying to integrate this node.js module with our meteor application: https://github.com/mifi/hls-vod. However, the way it works is that you actually call the app.get(hls/) from your HTML5 video tag's src. I am wondering if there is a way to expect the call to this get using meteor. Since I can't integrate express with meteor I am having some trouble doing this. I am wondering if there is a way to have meteor receive HTTP requests and send back data as per the node module.
This post has been updated
To server http requests over meteor you need a router. I would recommend ironRouter. There was meteor router but Tom Coleman also built ironRouter.
You can use something like this:
Router.map(function () {
this.route('serverFile', {
path: '/pathonserver',
action: function () {
console.log(this.params); //Contains params
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.end('hello from server');
}
});
});
Hopefully that should get the route working similar to the express router.
Meteor Router is now deprecated for Iron Router.
See here for Server Side Routing with Iron Router
You directly use the underlying webapp as illustrated here
or flow-router
or picker for SSR routes.