How to successfully use express routing in electron project? - node.js

I am using ExpressJS in my Electron project. The routing with Express doesn't work as expected.
Here is how I created the routing (in the main process):
const express = require('express')
const app2 = express()
app2.get('/requests/:_id', (req, res, next) => {
console.log('Dynamic Link WORKS!!');
hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){
res.json(request)
// res.sendFile(path.join(__dirname+'../homePage.html'))
});
});
And in the front-end I have the following:
{{this._doc.status}}
When I click on {{this._doc.status}} the it takes me to empty white screen with nothing printed in the console.
Can I have some guidance on how to implement ExpressJS routing in Electron?

Just a shot in the dark but you won't be able to connect without a port. Try adding this to the end of your server file. 'app2.port(9000)` then try hitting the same URL but with a port.

Electron has basically two process main and rendered process, when you are printing console.log, it is basically printing in your main process's console. You have to pass data to renderer process to show in console of your web page.
UPDATE - 2
Make express sever to listen to some port, then from frontend hit the url having that port also.
Main.js
app2.get('/requests/1234', (req, res, next) => {
console.log('Dynamic Link WORKS!!');
hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){
res.json(request);
// res.sendFile(path.join(__dirname+'../homePage.html'))
});
});
app2.listen(5000, function () {
console.log('Example app listening on port 3000!');
});
frontend
{{this._doc.status}}
After this it is working at my end.
If you want to run the express server in cluster mode, you should fork the process and try running the express server in new process.

Related

Where do you see console.log statements inside a POST request NodeJS express server?

I have an express server in NodeJS. It has a POST request with console.logs inside of it. Where Can I find the console.logs?
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const PORT = 5000;
app.get('/', (req, res) => {
console.log("this appears in the browser");
});
app.post('/login', (req, res) => {
console.log("where do I see this text??");
});
app.listen(PORT, '0.0.0.0', function() {
console.log("Server started (this text appears in the terminal)");
});
I'm running the server from Command Prompt. console.logs that aren't within a request appear in it. Where do the console.logs in the POST request function appear? I ask because I would like to see what's going on with the logic inside a more sophisticated POST request.
When you run the Node.js server directly from cmd, it should start the server and listening to the port specified. Now, when you start to hit the route/s all the console.log o/p to the terminal window not to the browser console window. Check the image for reference.
It will appear in the same terminal that you put the server to run.

In what file do we connect react front end folder files with back-end folder files with server.js and mysql database connection?

I have front-end folder files with react components and front-end css libraries.
In different folder, I have back-end files with server.js routing with mysql connection.
When I enter inputs on the screen, the inputs are not saved to mysql database.
Questions:
In what file, do I connect my front-end with back-end?
What statement should I use to connect my front-end with back-end?
To start Front-end, I used: npm start and To start Back-end, I used: nodemon server.js.
Question: When I connect front-end and back-end, what file should I open so that the front-end talks with the back-end -> both are starting?
Question 1 answer
You can do this a number of ways. I've done this with Serverjs and react in the
following manner.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 80085;
const app = express();
const token = 'impossiblylongimportanttokenhere';
let nextId = 7;
You'll need to import CORS, a Parser, Express for routing purposes.
Assuming you'll have a login you'll want a authenticator function. Please note this is just for development.
function authenticator(req, res, next) {
const { authorization } = req.headers;
if (authorization === token) {
next();
} else {
res.status(403).json({ error: 'User must be logged in to do that.' });
}
}
You'll probably want to replace that with something more secure once you're don with development.
with app as our router express has several CORS methods to get us started likepostget
Here's an example of one if we had an array called friends and if we wanted to find that friend by ID.
app.get('/api/friends/:id', authenticator, (req, res) => {
const friend = friends.find(f => f.id == req.params.id);
if (friend) {
res.status(200).json(friend);
} else {
res.status(404).send({ msg: 'Friend not found' });
}
});
The best part is that express has a method called listen that will start as soon as we hit NPM RUN on a cli that's parked in the same file location as server.js. Make sure to specify a port that your system isn't already using
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});
Question 2
In order to get connect to Server.js on our side you'll want use axios to make a GET/POST etc. call to whatever route you've made in your server.js above in the example it would be
.post('/api/friends', this.state.addFriend)
The biggest thing is you'll want multiple terminals running in order to have both the backend and the front end running at the same time. Start with backend first.

Why nodejs restarts every time I refresh the page on the client side

I am new to nodejs and did some test on my nodejs app. The code is basically like this.
import express from 'express';
import jsonfile from "jsonfile";
const app = express();
const PORT = process.env.PORT || 3002;
let global=0;
app.use(express.static(`${__dirname}/assets`));
app.use((req, res, next) => {
//write file
const file = '/path/data.json';
var obj = {
name:'cd'
};
jsonfile.writeFile(file,obj,{spaces: 2}, (err)=>{
console.error(err);
})
next();
})
app.get('/test', (req, res, next) => {
global++
res.send(''+global);
})
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
I built it on localhost, and input http://localhost:3002/test into the browser. The app will send the global counter to the browser, but if I refresh the page, I found my nodejs app restart and the counter doesn't change. If I comment out the jsonfile.writeFile part and do the same process like before, the nodejs app won't restart and the counter will increase every time I refresh the page. Why is that?
As you've commented the nodemon forces the page reload (live reload) to enable you to see the changes instantly.
Use node <your_script_name.js> or node <any_command_defined_in_scripts> (whatever is applicable) instead of nodemon if you don't want auto-refresh every time when you refresh the page.
Hope this helps!

Error: connect ECONNREFUSED node.js (express) and express-http-proxy

There was a problem making me crazy. For the third day I fight over it. There are two files, app.js and api.js
// app.js
const app = require('express')();
const proxy = require('express-http-proxy');
app.use('/api', proxy('http://localhost:1234'));
app.use((err, req, res, next) => {
console.log(err.message);
});
//api.js
const app = require('express')();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/bookshop');
var Users = require('./models/users');
Below in the file, there is a usual treatment to routes...
At the end of api.js, it is indicated that this script is being listened on port 1234:
app.listen(1234, err => {
if (err) console.log(err);
console.log('worked on http://localhost:1234');
});
Inside api.js there should be an access to the routes and to the database, but it does not reach the point of contact, because when I access the site I get the following:
"connect ECONNREFUSED 127.0.0.1:1234"
This message returns this middleware from app.js:
app.use((err, req, res, next) => {
console.log(err.message);
});
In package.json in "scripts" I indicated that the server app.js (3000 port) and the server api.js (1234 port) would be launched, but when updating the page on the site, occurs appeal to the address localhost:3000/api/users, but not localhost:1234/api/user, how it should be.
Help overcome this misfortune! There are no forces at all, I scoured the whole Internet in search of a solution to the problem , but the solution to the problem has not been found...
P.S. On the work computer this code works fine, but at home flatly refuses. At work x32 windows 8.1, at home x64 windows 8.1, if this is important.
netstat -a | findstr LISTEN
returns this: https://ibb.co/hyrxe5 (link to screenshot).
I also wanted to add that if I run the scripts separately, i.e. in one terminal call "node app.js" and in the second "node api.js", everything works fine
What is the problem? (sorry for my ugly english)

test express API requires local server

I've read i can run mocha test in an Express application (nodeJS) with super test and therefore it is not required to run the app in a different terminal session.
Whatever i try it always ends with a connection error.
To configure our continuous integration it is evident the integration and unit test (mocha, supertest, should) should be able to run without the node server is also running
The written tests are to validate our app's internal api end points
Who can explain how to run the tests without running the express server of the app so they can be integrated with for example strider
You need to split out your production code that calls app.listen and make sure that does not get executed during a mocha test run. I put all of my routes and settings code in app/index.js and then have a separate file app/server.js that has just a tiny bit of code to start listening, connect to the database, etc. But most of my application details are configured in app/index.js so I can test them with supertest.
//index.js
var app = require("express")();
app.get("/", function (req, res) {
res.type("text");
res.send("Welcome home");
});
module.exports = app;
//server.js
#!/usr/bin/env node
var app = require("./index");
app.listen(3000);
//index.mocha.js
var app = require("./index");
var request = require("supertest")(app);
var expect = require("expectacle");
describe("the home page", function () {
it("should welome me in plain text", function(done) {
request.get("/")
.expect(200)
.expect("Content-Type", "text/plain; charset=utf-8")
.end(function (error, result) {
expect(error).toBeFalsy();
expect(result.text).toBe("Welcome home");
done();
});
});
});

Resources