Difference between express.js and axios.js in Node - node.js

We use axios for http requests such as get, post, etc.
We use express for the same purpose also.
However according to what I read, they are for different purposes.
Please explain how.
PS: If you explain it by giving an example, it would be great!

You can think of express.js as a warehouse:
app.get('/item/:name', async function (req, res) {
res.send(await findItemByName(req.params.name));
});
If you want to get an item, for example a pencil, from this warehouse, you can use axios.js.
axios.get('/item/pencil')

Axios is used to send a web request whereas express is used to listen and serve these web requests.
In simple words, express is used to respond to the web requests sent by axios.
If you know about the fetch() method in javascript, axios is just an alternative to fetch().

I would say that express is used to create HTTP servers. So the server runs somewhere and responds to a request.
Axios is an HTTP client. It creates requests!

In very simple words axios is just passing the web request to the server-side (express). They basically work together (axios -> express -> DB)

Related

get data from webhook telegram bot with node js

I set the server address for the bot with /setwebhook, now how can I get the data with only node js and https package to access {message :{...} }? (like /getupdates method) but by webhook , probably I mean like the php code but in node js: file_get_contents("php://input") .
Should I use async or https.createServer ? If yes, how and please explain a little
You have to create a server that will handle receiving the data. You can do this by using http.createServer or, more conveniently, using a library such as Express. Simple implementation using Express would look like this:
const app = express();
app.post(`/api/telegram${process.env.TELEGRAM_BOT_TOKEN}`, async (req, res) => {
const message = req.body.message || req.body.edited_message;
...
});
In this example, I use bot token in the webhook url (since I and Telegram are the only entities that know the bot token, I can be sure that the requests to the url come from Telegram). There are better ways to make the webhook secure, such as using secret_token as specified in the docs for setWebhook method.
For development purposes, you can use a service like ngrok to redirect requests from the bot webhook to localhost.
To get an idea of a fully functioning example of implementing webhook with node.js and Express, you can check my open-source project on Github.

NodeJs Express how to handle items(params) that sent from frontend?

Im new in backend development (using NodeJs Express).
Its very basic question (I didn't find any good tutorial about it)
Question is:
I have this line of code:
app.get('/test', function (req ,res){
res.send('test');
});
What I wanna do is: BackEnd only sends res to FrontEnd, if FrontEnd send some JSON first.
Like Backend will show Something to FrontEnd, only if FrontEnd send JSON first;
How to handle it? What code to write?
Or what to type in google search to find this kind of tutorial
You are building a REST API with node. In REST we don't keep states. When we receive a request we process and respond. In the Front end, you can do wait until the response is received. use promises, async-await or callbacks to wait until the response in the Front end. Use these methods to connect with back end from front-end axios, fetch. To process the incoming JSON body use body-parser. Based on the request body you can process and send the response. PS: Every request should be given a response. That's how REST behaves.
In Query
yourbackend.com/test?message=welcomeToStackOverflow
This is how you can access with in query:
const {message} = req.query;
console.log(message);
// welcomeToStackOverflow
In Params
yourbackend.com/test/:message
This is how you can access with in params :
const {message} = req.params;
console.log(message);
// welcomeToStackOverflow
Here you have working example : https://codesandbox.io/s/trusting-rosalind-37brf?file=/routes/test.js

What does http and https module do in Node?

Can someone help me in understanding what does http and https module do in Express?
I was going through the following docs on w3schools
From definition it says
Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper Text Transfer Protocol (HTTP).
With following example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
This is the example to live demo
First, I am unable to comprehend their example like Where are they making (route) request so that they are receiving response?
Second by the definition, to make a request, using libraries like axios can be alternative?
third, when we make an api request, isn't the data transferred over http/https?
app.post("/", (req, res) => {
In short, Can someone please explain me in more human words the use of http package in express?
Update: I might be confusing this with express, I am used to using express and here we aren't using express
1- They aren't defining any route. That piece of code only creates a server running on port 8080 that when it's created or accessed on the home route (/) returns "Hello World". If you want to define routes you should take a closer look to a module called express that it's used by most of node users due to its simplicity and documentation (https://expressjs.com/en/starter/hello-world.html) In that link you have an example for creating the server and a basic route
2- Yes it can and should be because they are way better than the default from nodeJs. Take a look at axios or superagent, superagent it's better if you want to use formdata to send images or attachments.
3- By default, all servers created using http or express are http servers (don't have a certificate to encrypt the data so they aren't secure). If you want a https server, you can buy certificates or use https://letsencrypt.org/ this module that generates free SSL certificates with 1 month validation.
http module has multiple functions, it can be used to create a server, to make http requests and so on. It's up to you to decide which submodule from the package you want to use. Express is built over the http module making everything easier.
If you need more explanation, tell me and I will try to explain a little better.

Connecting frontend and backend MERN stack

How does the react client connect to the server via express? Many tutorials talk about Superagent and axios which is adding to my confusion. Are there any resources on server side routing in the context of react? thank you
In MERN stack, you do not necessarily have to think of the entire stack as a single entity. Mongo, ReactJS and NodeJS server can all work independently. And let us for easiness of understanding sake say all of them are on separate servers. That is we can have Mongo on one server, ReactJS on another server and NodeJS with express on a third server, then also it will be a MERN stack app.
How a MERN app work is as follows
For example, let us have an app that displays the details of all the students in a class. First, in the React app let us say you select a class, and then the React front-end will send a query to the nodejs server. The query will contain the particular class name. Now nodejs will send a query to the mongo db asking for the details of the students of that class which it will send back to the node server. The node server will then send the details to the front end and it will update it.
If you ask for connection as such, there can be no connection at all except for querying for data. Instead of using the reactjs front end you can use some other frontend and it will give you the same details. React, Mongo and Node, all are capable of working on their own in their respective fields.
Axios is a promise based HTTP client for the browser and node.js.
They are completely independent. Whether using axios, the native Javascript fetch, jQuery AJAX, etc...each of them runs in the browser and makes a GET/POST request to nodejs. You will have defined corresponding GET/POST routes within nodejs to respond to these requests and return JSON response data for them to consume.
I would start by forgetting about react altogether. Instead build an express API with various GET/POST routes that return JSON responses. Test with a simple client like postman. Once you have a handle on that, then start with a front-end Javascript framework to consume these services.
Here is a cut of my express+react api:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', {myjson: "myValue"});
})
module.exports = router;
Basically I am sending the json string to index.jsx, where the frontend is rendered.
Also I've set in express as:
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', reactViews.createEngine());
So the express server knows where React is.
Checkout the npm package Express-react-engine.
All the elements of the stack can be used independently, React , Node.Js, and MongoDB.
They can be installed in different servers and the communication is by using Fetch, Axios or any other tool.

create-react-app with Express

I need to query a database and I'm using create-react-app. The library to connect to the DB (pg-promise) does not work with Webpack and needs to be running on a Node server.
So I installed Express and have this:
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
})
How can I load data from the database from the React pages? I though of using request but how can I make a request to my own server? And what should I add to the lines of code above? I think it would be something like:
app.get('/query/:querybody', (req, res) => {
// process and return query
})
Is this right? How can I make it work with a SPA?
Probably the most friction-free method would be to have a separate app.js or server.js along side your CRA application. You can use a tool like concurrently to run both your React app and the express app.
The trick is to serve your express app on a different port than the default :8080 that CRA serves on. Usually 8081 is a good choice, as it's a common convention to use port numbers that are close together when developing.
In your React app, you will need to make sure you use the full URL for the express endpoint: http://localhost:8081/query/...
On the server side you are going in the correct direction: you need to setup endpoint which will respond with data based on request. In you example you setup an endpoint for a GET HTTP request. If you will need to pass a complex request (for example add new record to database), consider using POST HTTP requests.
On the client side (in the browser) you will need a library that will assist you in sending requests to your server. I can recommend to try Axios (https://github.com/mzabriskie/axios). Usually if you omit protocol, server name and port, request will be sent to the server from which the page was loaded:
http:127.0.0.1:8001/api/endpoint => /api/endpoint

Resources