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)
Related
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.
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.
I am new in nodejs and I just started to play a little with it and middlewares, I looked at some online documentation and did the exact same thing but my middlewares are not being called, I have maximally simplified my problem, so here is the issue:
const express = require('express')
const port = 3000;
const app = express();
app.use( function(req, res, next) {
console.log("Middeware 1 being executed");
next();
})
app.use( function(req, res, next) {
console.log("Middeware 2 being executed");
next();
})
app.listen(port, () => console.log(`Listening on port: ${port}`));
But when I execute this code, in the console I can only see the "Listening on port: 3000" message, why my middlewares are not being executed, this is so weird and I am totally frustrated. Can someone explain what is going on here? Why are they not being executed at all?
Open http://localhost:3000/ in your browser and you will see that logs.
Middleware will be executed by a request from the client.
Middlewares are executed when requests are made. So, if you open a browser and try to open server by http://localhost:3000, you will see your two middlewares being called.
http://expressjs.com/en/guide/using-middleware.html
Good luck.
So I'm using webpack for a project on 8080 with a backend on 3000. The proxy seems to work fine, as I can send requests to the backend and access it without issue. However. I need to include this middleware that allows me to have a user load the page, and if they've logged in within a certain amount of time, the initial request they send to the server logs them in automatically.
router.use(function (req, res, next) {
//check token for routes beneath vvvv
})
router.post('/preauth', function (req, res) {
//return user account info if req.token is valid
})
When I try to get to prauth, or even any route before that from the page loaded on 8080 I only touch the middleware and nothing else.
When I do npm run build then try it again from the identical page on 3000, it works as expected.
No, CORS is not enabled and the proxy does not rewrite any url.
Does anyone know if something in my Webpack config might be causing this?
You need install Cors in nodejs:npm install cors, you can try the following below or you see: Nodejs + Vuejs
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('This is a CORS-enabled web server listening on port 80')
})
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.