I am getting an error while running node server. The error is
I also tried many solutions given in example, but nothing is working. ng serve is working. I've created a server file and also installed node express module. I've followed these instructions to create the server.
Server.js file code is
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname,'dist')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api',api);
app.get('*',(req,res)=>{
res.sendfile(path.json(__dirname,'dist/index.html'));
});
app.listen(port,function(){
console.log("server is running on localhost: " + port);
});
and server/routers/api
const express= require('express');
const router = express.Router();
router.get('/',function(req,res){
res.send('api works');
});
module.exports= router
Related
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);
I am new in node js and want to build an application in which they are multiple APIs and all are settled in routes folder but here is the problem when I tried to call the API in index.js(main file) its only take one route either userAPI or cleanerAPI.
As both APIs have different URL.
var mongoose = require ('mongoose');
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const routerUser= require('./routes/userAPI')
mongoose.connect('mongodb://localhost:27017/Covid');
app.use(bodyParser.json());
app.use('/',router);
app.listen(4000,function(){
console.log("Server Running on 4000")
});
you can try this one also.
Main file(index.js or server.js)
const appRoutes = require('./Routes')
appRoutes(app)
Routes(index.js)
module.exports = app => {
app.use("/user", require('./users'));
app.use("/cleaner", require('./cleaner')); };
Routes(users.js)
const express = require('express');
const router = express.Router();
router.route('/list')
.post(function(req,res){......});
module.exports = router;
In my node/express app, I have the following app.js file with the following routing
const express = require('express');
const path = require('path');
const logger = require('./middleware/logger');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/wsserver', require('./routes/wsroutes'));
app.use('/', require('./routes/company'));
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log('server runs on port ', port);
});
Every request that goes to http://localhost:8080/wsserver, is handeld by wsroutes. I am planning to setup a websockets server in there, but for now contains
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('ws');
})
module.exports = router;
The / handles all the other requests and its handled by the company that contains
router.get('/',(req, res)=>{ ....
router.get('/:companyName/:id?/:employ?',(req, res)=>{ ...
etc
As you can guess, the problem is that when I go to http://localhost:8080/wsserver, is handled by the / route and the company route. I get the interface and the message no company named wsserver , because the wsserver becomes an argument in the router.get('/:companyName/:id?/:employ?' route.
How can I still have both routes, not change the / one and have them both work correctly? I tried to change positions in the routes like so
app.use('/', require('./routes/company'));
app.use('/wsserver', require('./routes/wsroutes'));
ans still nothing.
What else can I do ?
Thanks
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.
I am trying to create nodejs express application, I am facing weird issue while using routes
This is how my server.js looks
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api',api);
app.use(express.static(path.join(__dirname,'dist')));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname,'dist/index.html'));
});
const port = process.env.port || 3000;
app.set('port',port);
const server = http.createServer(app);
server.listen(port,function(){
console.log('server running at port '+port);
});
I am getting following error "node_modules/express/lib/router/index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
"
Please let me know where I am going wrong
I just forgot to add module.exports = router in my api.js adding this solved my problem