I'm just learning how to use Node.JS and I'm trying to set up an express server, but when I try to test the route and do the GET request in Postman it throws an error. What is wrong with my code below?
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const logger = require("morgan");
const cors = requiere("cors");
const port = process.env.PORT || 3000;
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(cors());
app.disable("x-powered-by");
app.set("port", port);
server.listen(3000, "192.168.1.36" || "localhost", function() {
console.log("aplicacion de NodeJS " + port +" iniciada...")
});
app.get("/", (req, res) => {
res.send("Ruta raíz del backend");
});
// ERROR HANDLER
app.use((err, req, res, next) => {
console.log(err);
res.status(err.status || 500).send(err.stack);
});
What Postman tells me does not clarify much where the error is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>
you made a typo here requiere("cors") it must be require and also you must import express const express = require('express')
const express = require('express')
const app = express();
const logger = require("morgan");
const port = process.env.PORT || 3001;
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.listen(port, function () {
console.log("aplicacion de NodeJS " + port + " iniciada...")
});
app.get("/", (req, res) => {
res.send("Ruta raíz del backend");
});
Related
When I make this post request on postman -
http://localhost:5000/api/edit/links?editData={"editData"[{"link":"www.github.com/","name":"link name"},{"name":"link name","link":"linkdata"}]}
I get the following error:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/edit/links</pre>
</body>
</html>
My server Index file looks like this:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const cors = require('cors');
require('dotenv').config();
require('./db/connectDB');
//Import routes
const authRoute = require('./routes/auth');
const editRoute = require('./routes/edit');
const publicRoute = require('./routes/public');
//Middleware
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Route Middlewares
app.use(cors());
app.use('/api/user', authRoute);
app.use('/', publicRoute);
const PORT = 5000;
app.listen(PORT, () => console.log('server is up and running '));
The route I'm trying to reach is in this file
edit.js
const router = require('express').Router();
const verify = require('./verifyToken');
const {editLinksValidation} = require('../validation');
const ObjectId = require('mongoose').Types.ObjectId;
const User = require('../model/User');
const fetchFavicon = require('#meltwater/fetch-favicon').fetchFavicon;
router.post('/api/edit/links/:editData', verify, (req, res) => {
const editData = JSON.parse(req.params.editData);
User.updateOne(
{_id: id},
{
$set:
{
links: editData
}
}
).then(metadata => res.send(metadata))
.catch(err => console.log(err));
});
What am I doing wrong here?
As the error says, there is no route defined for /api/edit/links for the POST method. And indeed your code shows that your route is /api/edit/links/:editData -- that last path element cannot be empty. Not sure what your intention was with that, but I have the hunch that your intention was to get the value from the query instead, in which case you'd want to use:
router.post('/api/edit/links/', verify, (req, res) => {
const editData = JSON.parse(req.query.editData);
You don't use imported editRoute in the server index file at all.
I suppose you should add this line:
app.use('/', editRoute);
when i open my app for the first time it work just fine but when i refresh the page it give me a url to my index.html file ( /client/build/index.html ) , i have deploy it on heroku
that is the code in my app.js file that create the server
const express = require('express');
const app = express();
const path = require('path');
// create a server for socket io
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
module.exports = io = socketio(server);
// my middle ware
const morgan = require('morgan');
const bodyParser = require('body-parser');
// Init Middelware
app.use(express.json({ extended: false }));
// my router
const postRoute = require('./nodeapi/routers/post');
const authRouter = require('./nodeapi/routers/auth');
const usersRouter = require('./nodeapi/routers/users');
const friendRouter = require('./nodeapi/routers/friend');
const chatRouter = require('./nodeapi/routers/chats');
const mongoDB = require('./nodeapi/mongodb-database/db');
const port = process.env.PORT;
// Connect monogo database
mongoDB();
// Middel ware
app.use(morgan('dev'));
app.use(bodyParser.json());
// Get the routes
app.use('/', postRoute);
app.use('/', authRouter);
app.use('/', usersRouter);
app.use('/', friendRouter);
app.use('/', chatRouter);
app.use('/file/', express.static('./uploads/'));
// connect to socket io
io.on('connection', (socket) => {});
//Serve static assets in productio
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.send(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});
}
// listen to the port
server.listen(port, () => {
console.log(`this is port ${port}`);
});
this is when i open it for the first time
this is when i refresh the page
You just need to send it as file not a text
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});
The following is an excerpt from some server side code located in the entry point of the application:
const app = express()
const chatServer = require('http').Server(app);
chatServer.listen(3000)
const io = require('socket.io')(chatServer);
io.on('connection', (socket) => {
console.log('ABC')
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message', message)
})
});
Upon running my dev server I expected to see 'ABC' print once to the console. However, it is printing three times (ABC, ABC, ABC) instead. Why does this happen? The io variable is NOT used anywhere else in the application. I'm pretty sure it has nothing to do with client side logic (since no requests are made by the client at this point) And for complete reference, the entire app.js code is displayed below:
const express = require('express')
require('./db/mongoose')
const playerRouter = require('./routers/player')
const contractRouter = require('./routers/contract')
const bodyParser = require('body-parser');
const hbs = require('express-handlebars')
const path = require('path')
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
// Define paths for Express config
const viewsPath = path.join(__dirname, '../templates/views')
const partialsPath = path.join(__dirname, '../templates/partials')
const layoutPath = path.join(__dirname, '../templates/layouts')
const app = express()
const chatServer = require('http').Server(app);
chatServer.listen(3000)
const io = require('socket.io')(chatServer);
// Passport Config
require('./middleware/passport')(passport);
//Setup handlebars engine and views location
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'main',
layoutsDir: layoutPath,
partialsDir: partialsPath,
}));
app.set('view engine', 'hbs')
app.use(express.static('public'))
app.set('views', viewsPath)
io.on('connection', (socket) => {
console.log('ABC')
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message', message)
})
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())
// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Connect flash
app.use(flash());
// Global variables
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.currentUser = req.user
next();
});
app.use(playerRouter)
app.use(contractRouter)
module.exports = app
Here is the client side code (for brevity I did not include the entire HTML file):
const socket = io('http://localhost:3000')
const messageContainer = document.getElementById('message-container')
const messageForm = document.getElementById('send-container')
const messageInput = document.getElementById('message-input')
socket.on('chat-message', message => {
appendMessage(`Opponent: ${message}`)
})
messageForm.addEventListener('submit', e => {
e.preventDefault()
const message = messageInput.value
appendMessage(`You: ${message}`)
socket.emit('send-chat-message', message)
messageInput.value = ''
})
const appendMessage = (message) => {
const messageElement = document.createElement('div')
messageElement.innerText = message
messageContainer.append(messageElement)
}
Sure, the message 'ABC' is rendered every time a connection to the client is established.
const express = require("express");
const path = require("path");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
// Here declare fiel static, as index.html, css, javascript.
app.use(express.static(path.resolve(__dirname, "../public")));
io.on("connection", socket => {
console.log("ABC");
socket.on("send-chat-message", message => {
socket.broadcast.emit("chat-message", message);
});
});
http.listen(8080, () => {
console.log("Starting...");
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="message-container"></div>
<form id="send-container">
<input id="message-input" type="text" />
<button type="submit">submit</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
const socket = io();
const messageContainer = document.getElementById("message-container");
const messageForm = document.getElementById("send-container");
const messageInput = document.getElementById("message-input");
socket.on("chat-message", message => {
appendMessage(`Opponent: ${message}`);
});
messageForm.addEventListener("submit", e => {
e.preventDefault();
const message = messageInput.value;
console.log(message);
appendMessage(`You: ${message}`);
socket.emit("send-chat-message", message);
messageInput.value = "";
});
const appendMessage = message => {
const messageElement = document.createElement("div");
messageElement.innerText = message;
messageContainer.append(messageElement);
};
</script>
</body>
</html>
Here you can see the code working live.
I hope it helps. Any questions comment.
https://codesandbox.io/s/expressjs-chat-9v8lo
So, I have the simple dream to start the Server with Socket.io library, but for some reasons it's does not happen... I cannot understand what is wrong, because I do not gets even the standart message on server run - Server running on port ${port}.
Help, please...
'use strict'
const express = require('express');
const http = require('http');
const io = require('socket.io');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt-nodejs');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const app = express();
const server = http.Server(app);
const socketServer = io(server);
const router = express.Router();
const chat = require('./routes/chat');
const profile = require('./routes/profile');
const registration = require('./routes/registration');
const login = require('./routes/login');
const logout = require('./routes/logout');
const EmployersSchemaDB = require('./SchemaDB/EmployersSchemaDB');
const MessagesSchemaDB = require('./SchemaDB/MessagesSchemaDB');
const User = require('./SchemaDB/ShemaAuthtificaion');
mongoose.connect('mongodb://test_db');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
res.setHeader('Cache-Control', 'no-cache');
next();
});
app.use(session({
secret: 'work hard',
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
app.use('/', router);
app.use('/chat', chat);
app.use('/profile', profile);
app.use('/auth/login', login);
app.use('/auth/logout', logout);
app.use('/auth/registration', registration);
const port = process.env.API_PORT || 8989;
socketServer.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Change from this:
socketServer.listen(port, () => {
console.log(`Server running on port ${port}`);
});
to this:
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
You need to start your http server. That's the core server here that works with both Express and socket.io and fields all incoming requests.
Your variable socketServer and your io variable are misnamed (which is probably part of your confusion). socketServer is the actual server, that's the socket.io server-side instance which is typically named io. See the socket.io server doc for details.
You should start with a simpler server:
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
const socket = socketio(server);
app.use(express.static(`./public`));
socket.on('connect', socket => {
socket.emit('identify', {'server':'server data'});
});
socket.on('data', data => {
console.log(data);
});
server.listen(4000, () => {
console.log('Server up and running on port 4000');
});
In the front end you can test this like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>test
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script type="text/javascript">
'use strict';
var socket = io('http://localhost:4000');
socket.on('identify', function (socket) {
console.log(socket);
});
</script>
</body>
</html>
I am trying to create and start a server and I've been looking at other code and can't see why mine isn't working (just getting this: localhost just keeps loading and loading and nothing happens).
Any ideas? Thanks!!!
app/server/app.js :
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = http.createServer();
server.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
app/browser/index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>node</title>
</head>
<body>
<div>
<p>Hey whats up</p>
</div>
</body>
</html>
Your code works for me.
The only thing wrong in your code is you have to change server.listen(1337, function ()..., to app.listen(1337, function () {...
Also, I added a file path...
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));})
...to link your localhost:1337 to your index.html file. Now your index.html file will display when you go to localhost:1337.
Lastly, I'm not sure if you need this line... var server = http.createServer();. I deleted it and everything worked fine.
Here's the code below.
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));
})
app.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
Maybe the port You wrote - 1337 is busy, check by choosing other port, for example 4200, or 3000 - server.listen(4200,function () {