A little info
I got my client (localhost:8080) and my server.js (localhost:3000). I made some routes for my server.js (see the file below).
Question
Now, if I try to access the route on my server e.g. localhost:3000/users/4, I get the expected result - 4 fake users are created. However if I try to append the postfix users/4 to the client: (localhost:8080/users/4), I get an error! Cannot GET /users/4. Likewise I get an cannot GET *SOMETHING* error if I try one of the other routes.
Have I misinterpreted something? Shouldn't I be able to append the route to the client url and then get the res (respons) back again? (as long as the server is running of course, or is that not how it works?)
routes.js (I got all my routes in this one file)
var faker = require("faker");
var appRouter = function (app) {
app.get("/", function (req, res) {
res.status(200).send({ message: 'Welcome to our restful API' });
});
app.get("/user", function (req, res) {
var data = ({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email()
});
res.status(200).send(data);
});
app.get("/users/:num", function (req, res) {
var users = [];
var num = req.params.num;
if (isFinite(num) && num > 0 ) {
for (i = 0; i <= num-1; i++) {
users.push({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email()
});
}
res.status(200).send(users);
} else {
res.status(400).send({ message: 'invalid number supplied' });
}
});
};
module.exports = appRouter;
Server.js
var express = require("express");
var bodyParser = require("body-parser");
var routes = require("./routes/routes.js");
var app = express();
const server_port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
routes(app);
var server = app.listen(server_port, function () {
console.log("app running on port.", server.address().port);
});
You must be mixing up something there. When you open http://localhost:8080/users/4, then what you are doing is a SERVER request to localhost:8080 with the route users/4. The client in your scenario is a browser which is making a request to the server.
Now if your server is actually running on localhost:3000, then you must be running another server on localhost:8080. So if you want to be able to make a request to http://localhost:8080/users/4, then you need to configure your server on localhost:8080 to accept that route, not the one on localhost:3000.
Related
I am trying to make Postman work with React JS using express. I am following a Mern Stack Development tutorial in free code camp. I have Cors extension enabled in my browsers, both in Chrome and in Edge. I keep getting this message in localhost:5000 "Cannot get /" and get this message {"msg":"This is CORS-enabled for an allowed domain."} in localhost:5000/users/add. My code looks something like this:
This is my server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology:true});
const connection= mongoose.connection;
connection.once('open', () =>{
console.log("Mongodb database connection established successfully");
})
const exercisesRouter= require('./routes/exercises');
const usersRouter= require('./routes/users');
var allowlist = ['http://localhost:5000']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use('./exercises',exercisesRouter);
app.use('./users', usersRouter);
app.get('/users/add', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})
app.listen(port, ()=>{
console.log(`Server is running on port: ${port}`);
});
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
cords don’t have anything to do with this
Can you tell me where is yow route for “/“ something like this
app.get(“/“, (req,res)=>{
…..
});
Yes exactly. You don’t have it. If the route/endPoint is not declared how do use expect them browsers to show you some else
When browssers open yow link at localhost:5000
They make a get request to “/“. So express just tell’em
Can not get “/“
I do not
I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js
I would use sockets in a separate route file .
I'm using the method mentioned in this answer : Express 4 Routes Using Socket.io
I have copied exactly the same logic. In server file :
var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes")(io);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
.... DB Configuration ....
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
io.on("connection", function (client) {
console.log("Un client est connecté !");
//routerProj(client);
});
app.use("/v1", routerProj, function (req) {
//Create HTTP server and listen on port 8000 for requests
});
My connection socket is working and the console.log runs in terminal
routes.js file
var express = require("express"); // call express
var router = express.Router(); // get an instance of the express Router
var admin = require("firebase-admin");
var returnRouter = function (client) {
router.use(function (req, res, next) {
// do logging
client.on('save-message', function (socket) { console.log("heheyy") })
});
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
list = JSON.stringify(list);
//list = JSON.parse(list)
console.log(err);
//console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
router
.route("/")
.post(function (req, res, err) {
console.log(req.body);
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
ref.push(
{
"text": req.body.text
}
);
});
return router;
}
module.exports = returnRouter;
save-message is emit in Angular when my arr is running :
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
Save-message event is not getting read neither the routes file, In my angular application services does not get data from routes. and console.log in get and post routes does not work.
My question is how to get sockets working in a reparate file ?
You should move the socket.io listener outside of the express use route. It's not really clear why you would want it there as it will register a new listener every time someone makes a request to your v1 endpoint.
You likely aren't seeing the messages because the listener does not register until someone makes a request to the v1 endpoint and the client already sent its message.
var returnRouter = function (client) {
// do logging
client.on('save-message', function (socket) {
console.log("heheyy");
});
...
};
I have a node.js (with express) module that connects to twitter and streams data based on search terms the user inputs in the front end (see: twitter.tweetStream(api, params, values, track, bridgeArray, usernameArray, scoreData);). The module executes when the user submits a form and is directed to /test, but it continues to run even after they leave /test. It also runs in parallel with any new instance of it that starts.
Is there a way to tell the module to stop running if the user leaves the /test route? Th
// Renders form on default Route
app.get('/', function(req, res){
res.render('form');
});
// On form submission take data and passes it into twitter stream call as "track" object then renders the 'tweets' feed
app.post('/test',function(req,res){
var track = req.body;
twitter.tweetStream(api, params, values, track, bridgeArray, usernameArray, scoreData);
res.render('tweets');
});
// Renders Tweets stored in "values object" onto a page to be called from tweets template
app.get('/tweets', function(req, res){
res.render('home', {
profileImg: values.profileImg,
userName: values.userName,
screenName: values.screenName,
text: values.text,
timeStamp: values.timeStamp,
tweetScore: values.tweetScore,
// totals: values.totals
});
});
Complete code added for clarity:
var express = require('express');
var app = express();
//var http = require('http').Server(app); // Not using
var exphbs = require('express-handlebars');
var bodyParser = require('body-parser');
var twitter = require('./twitter.js');
var hue = require("./hue_control.js");
// Variable that control Twitter Calls
var api = 'statuses/filter';
var params = {slug:'REDACTED', owner_screen_name: 'REDACTED', skip_status: true};
var values = {};
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(bodyParser());
app.use(express.static('public'));
// Checks for Hue bridge on local network gets IP and sets usename
var bridgeArray = [];
var usernameArray = [];
var scoreData = [];
var track = {};
hue.activate(bridgeArray, usernameArray);
// Renders form on default Route
app.get('/', function(req, res){
res.render('form');
});
// On form submission take data and passes it into twitter stream call as "track" object then renders the 'tweets' feed
app.post('/tweets',function(req,res){
track = req.body;
res.render('tweets');
twitter.tweetStream(api, params, values, track, bridgeArray, usernameArray, scoreData);
});
// Renders Tweets stored in "values object" onto a page to be called from tweets template
app.get('/tweetstatic', function(req, res){
res.render('home', {
profileImg: values.profileImg,
userName: values.userName,
screenName: values.screenName,
text: values.text,
timeStamp: values.timeStamp,
tweetScore: values.tweetScore,
});
});
app.get('/totals', function(req, res){
res.render('totals', {
tweetTotal: values.tweetTotal,
score: values.score,
color: values.color
});
});
// App Settings
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Am working on a project using the mean stack.
Before setting up the client side am testing my routes using postman.
http://www.getpostman.com/
Am trying to send a post request to fetch a specific user and a post request to add a user.
This is the code....
//cons.js
'use strict';
var strg = 'mongodb://localhost/users';
module.exports={
strg:strg
}
//models.js
'use strict';
var mong = require('mongoose'),
str = require('./cons');
mong.connect(str.strg);
var pips = mong.model('pips',{
name: {type: String, required: true, index: { unique: true }},
pass: {type: String, required: true},
act:{type: Boolean}
});
module.exports = {
pips: pips
}
//user_ctrl.js
var addPips, getPipsById,
pip = require('./models').pips;
getPipsById = function(req, res){
/*pip.findOne({jina:req.params.unam}).exec(
function(err,rez){
if(err||!rez){
res.send(err);
}
res.json(rez);
})*/
pip.findOne({jina:req.body.unam}).exec(
function(err,rez){
if(err||!rez){
res.send(err);
}
res.json(rez);
})
};
addPips = function(req, res){
pip.create({
name: req.body.unam,
pass: req.body.upas,
act: false
}, function(err, rez){
if(err||!rez){
res.send(err);
}
res.send("User account created...");
})
};
module.exports = {
addPips: addPips,
getPipsById : getPipsById
}
//routes.js
'use strict';
var jada = require('./user_ctrl');
module.exports = function(app){
//app.get('/api/users/:unm',jada.getUserById);
app.post('/api/users',jada.getPipsById);
app.post('/api/users',jada.addPips);
app.all('/api/*', function(req, res) {
res.send(404);
});
};
//server.js
'use strict';
var express = require('express'),
morgan = require('morgan'),
port =process.env.PORT || 3000,
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express();
app.use(morgan('dev'));
app.use(bodyParser());
app.use(methodOverride());
app.use(express.static(__dirname+"/app"));
require('./config/models');
require('./config/user_ctrl');
require('./config/routes')(app);
app.listen(port);
console.log('Magic happens on port: '+port);
Am using a post request to fetch a specific user because I am picking information from the form and not the url.
When am adding the user. I get an error message: 'validation error name and pass required'. I don't seem to see where this is coming from because I am assigning values from the form to the parameters.
Can anyone tell me what am doing wrong? Thank you...
Well, it turns out that Express Body-Parser does not know how to deal with data when the content-type is not set.
I found out from here:
Express.js req.body undefined
I use postman to test my routes before building the client side. In postman, when simulating form posts I used x-www-form-urlencoded it sets the content-type automatically.
If you are getting undefined form values, try checking if your headers (content-type) are properly set.