how to route in nodejs with react? - node.js

I'm using front reactjs and backend nodejs. react address is localhost:3000, and node address is localhost:5000. I already set up my proxy at react with node. this porxy setting only works in react js. but I want to use api server using routing. for example when I type the url "localhost:3000/api/hello", it route to nodejs "localhost:5000/api/hello". is is possible?
here is my nodejs code.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 5000;
const fs = require('fs');
const moment = require('moment');
const data = fs.readFileSync('./database.json');
const config = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
host : config.host,
user: config.user,
password : config.password,
port : config.port,
database : config.database
})
const multer =require('multer');
const upload = multer({dest:'./upload'});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use('/image',express.static('./upload'));
app.get('/api/hello',(req,res)=>{
res.send({message:"Hello Charles!"});
});
app.listen(port,()=>console.log(`Listening on port ${port}`));

As suggested you should be using the same port here for serving static assets and serving APIs. Just by adding a few lines in existing code it can be done.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 5000;
const fs = require('fs');
const moment = require('moment');
const data = fs.readFileSync('./database.json');
const config = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
host : config.host,
user: config.user,
password : config.password,
port : config.port,
database : config.database
})
const multer =require('multer');
const upload = multer({dest:'./upload'});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use('/image',express.static('./upload'));
// ************All static files will be servered from here.***************
app.use(express.static(path.resolve(__dirname, '../build')));
// *************** You can initialize API's here.***************
app.get('/api/hello',(req,res)=>{
res.send({message:"Hello Charles!"});
});
// *************** Fallback if no route is matching, index.html will be returned.***************
app.route('*', function (req, res) {
res.sendFile(path.resolve(__dirname, '../build/index.html'))
});
app.listen(port,()=>console.log(`Listening on port ${port}`));
In the development mode, we can specify in the package.json for proxying requests while the app is run from npm start
"proxy": "http://localhost:5000"

Related

Browser showing "Cannot GET /api/posts/ " instead of "hello" from res.send('hello')

My index.js file:
//Dependencies
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const posts = require('./routes/api/posts.js');
//Configuration
const port = process.env.PORT || 5000;
//App object
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
//Main app
app.use('api/posts',posts);
//Starting server
app.listen(port,()=>{
console.log(`server running at ${port}`);
});
My Api file:
//Dependencies
const express = require('express');
const mongodb = require('mongodb');
//Mini app
const router = express.Router();
//Get post
router.get('/',(req,res)=>{
res.send('hello');
});
//Add post
//Delete post
module.exports = router;
I'm expecting to get "hello" in my browser but constantly getting "Cannot GET /api/posts/" in firefox and postman. What should I do now?
Correction :-
//Main app
app.use('/api/posts',posts);

Use of express-basic auth to simple prompt authentication in react app

I'm trying to make a simple prompt authentication for my react app and I've this file server.js:
const express = require('express');
const path = require('path');
const app = express();
const basicAuth = require('express-basic-auth');
const PORT = process.env.PORT || 5000;
app.use(basicAuth({
challenge: true,
users: { 'me': 'openforme' }
}))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
I want that when the user and pass are correct app use:
app.use(express.static(path.join(__dirname, '/client/build')))
to see my web page

No response from nodejs api

This is my code i tried to send a request through http://localhost:3000/api/post/article using postman but i received cannot get as error.
It's working without using router.get but instead using app.get, so i think the problem is with the router.
This is the server.js file
const http = require("http");
const app = require("./app");
app.set("port", process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
this is the app file
const express = require("express");
const postRoutes = require("./routes/post");
const app = express();
app.use("api/post", postRoutes);
module.exports = app;
This is the router file
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
router.get("/article", postCtrl.specArticle);
module.exports = router;
This is the controller file
module.exports.specArticle = (req, res) => {
res.status(200).json({ message: "working currently" });
};
Change this:
app.use("api/post", postRoutes);
to this:
app.use("/api/post", postRoutes);
As best I know, all paths in your route handlers should start with / (at least I have no idea why you would ever not start them with a /).

Heroku Error Cannot GET / Node/Express/Router

I am hosting postgres database and app on Heroku. Express Router was working on my local host. Since I have deployed to Heroku I get ERROR on index route. But URL routes work when typed in.
I have tried making sure the PORT is setup correctly.
I have tried testing to see if Express/Router actually works by changing routes.
I have tried the other answers on stack overflow.
I have checked my proct file.
app.js
```
const express = require("express")
const app = express()
const path = require('path')
const PORT = process.env.PORT || 8080
const mustacheExpress = require("mustache-express")
const blogsRouter = require('./routes/blogs')
app.use(express.urlencoded({ extended: false }))
const VIEWS_PATH = path.join(__dirname, '/views')
app.use("/css", express.static(__dirname + '/css'))
app.engine("mustache", mustacheExpress(VIEWS_PATH + '/partials', '.mustache'))
app.set("views", VIEWS_PATH)
app.set("view engine", "mustache")
app.use('/blogs', blogsRouter)
app.listen(PORT, () => {
console.log("Hey Nick the server is running...")
})```
blogs.js //Routes folder
```const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')
const SALT_ROUNDS = 10
const session = require('express-session')
const checkAuth = require("../utils/checkAuth")
const pgp = require('pg-promise')();
const connectionString = '#postgress host string is here'
const db = pgp(connectionString);
```
Do not know whats causing Express Router not to work on Heroku.

openshift express app serving static files

Noob here. I'm trying to build an api server on Openshift using express. I also want to be able to serve static files from the /static folder. The problem is, I can't figure out how to set it up on Openshift. I've tried everything I can think of.
I have 2 server files, the app setup which calls a router.js file for the routes.
app.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const env = process.env;
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
// default to a 'localhost' configuration:
var connection_string = '127.0.0.1:27017/api:api';
// if OPENSHIFT env variables are present, use the available connection info:
if(env.OPENSHIFT_MONGODB_DB_PASSWORD){
connection_string = env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
env.OPENSHIFT_MONGODB_DB_PASSWORD + "#" +
env.OPENSHIFT_MONGODB_DB_HOST + ':' +
env.OPENSHIFT_MONGODB_DB_PORT + '/' +
env.OPENSHIFT_APP_NAME;
}
mongoose.connect('mongodb://' + connection_string);
// App Setup
app.use(morgan('combined')); //logging middleware
app.use(cors()); // allow cross origin requests
app.use(bodyParser.json({ type: '*/*'})); //read requests as json
-----> do I need to put something here ????
router(app);
// Server Setup
const port = env.NODE_PORT || 3090;
const ip = env.NODE_IP || 'localhost';
const server = http.createServer(app);
server.listen(port, ip);
console.log('Server listening on: ', port);
router.js
const Authentication = require('./controllers/authentication');
const passportService = require('./services/passport');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false});
const requireSignin = passport.authenticate('local', { session: false});
module.exports = function(app) {
app.post('/signup', Authentication.signup);
app.post('/signin', requireSignin, Authentication.signin);
app.get('/health', function (req, res, next ) {
res.writeHead(200);
res.end();
});
----> and/or something here?
}
Everything works except serving static files. Not sure if I need to put something in the app.js file as middleware, in the router file or both. Also not sure if I need to use Openshift environment variables? Can someone nudge me in the right direction?
In express you can serve static files by adding the following to your app.js using express.static()
var path = require('path');
// put this before all of your routes
app.use(express.static(path.join(__dirname, 'static')));

Resources