I made a simple node.js server which shows index.html. When I run it on localhost it shows the page but when I try to run it on http:ip:8000 it says "This web page is not available".
This is my code:
// server2.js (Express 4.0)
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser()); // pull information from html in POST
app.use(methodOverride()); // simulate DELETE and PUT
var router = express.Router();
var notes = [
{username: 'Mohit1406', password: 'midkm' ,firstName: 'mxkz', lastName: 'ckzmk', dob: '1994-05-08', gender: 'male'},
];
router.get('/note', function(req, res) {
res.send(notes);
});
router.post('/note', function(req, res) {
var note = req.body;
notes.push(note);
res.send(note);
});
app.use('/api', router);
app.listen(8000,'0.0.0.0');
console.log('Open http://localhost:8000 to access the files now'); // shoutout to the user
app.listen(8000);
hostname is optional
server.listen(port, [hostname], [backlog], [callback])#
Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections directed to
any IPv4 address (INADDR_ANY).
Related
I want to create a simple API with a post method in which the string will be sent as a request.On debugging I found that that the string could not be parsed on logging it was showing undefined
I have tried app.use(express.json());
Also tried middleware functions but it didn't work.
INDEX.JS
const express = require('express');
const env = require('dotenv');
const bodyParser = require('body-parser');
//importing the express module
const app = express();
//creating the app
env.config();
app.use(bodyParser());
//get request for the first page which is set to be a default
app.get('/',(req,res,next)=>{
res.send('welcome to the first page');
console.log(`welcome to the ecommerce site which is oon the ip and port np ${process.env.PORT }`);
});
app.post('/data',(request,response,next)=>{
response.status(200).json({message:request.body});
console.log(response.body);
})
//creating an which listens on port 4000
app.listen(process.env.PORT,()=>{
console.log(`application running at the port ${process.env.PORT}`);
});
on posting XYZ or 'XYZ ' or "XYZ" it is printing at localhost:4000/data
{
"message": {}
}
I can't access my API/nodejs server [http://10.0.0.14:3000/] on another computer. If I search for [http://10.0.0.14:3000/] in the browser on my local computer the api is running on I get 'test' with statusCode 200 back. But if I try the same on another computer in the same network I get a timeout. Why does this happen?
const express = require('express');
const bodyParser = require('body-parser');
const { parse } = require('querystring');
const HOST = '10.0.0.14';
const PORT = 3000;
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.listen(PORT, HOST,function() {
console.log("Server is listening on port 3000...");
});
app.use(bodyParser.json());
app.get('/', function(req,res) {
res.header("Access-Control-Allow-Origin", "*");
// let body = req.body;
console.log("GET ", req.body);
res.send("test");
});
if it is windows add a rule to the firewall for incoming data for port 3000
I am building an api that will interface with the MongoDB database and have mounted it as a subapplication. I have defined a session variable in my server controller.
However, any time that the server files need to talk to the api files the session variables are never passed off.
Heres the app.js file
//app.js file
'use strict';
process.env.NODE_ENV = 'development';
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
app.use(helmet());
var port = process.env.PORT || 3000;
mongoose.connect("mongodb://localhost:27017/striv4");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use(flash());
// make user ID available in templates
app.use(function (req, res, next) {
res.locals.currentUser = {
username:req.session.username,
id: req.session.userId
};
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secreter'));
app.use(logger('dev'));
var api = require('./app_api/routes/index');
var serverRoutes = require('./server/routes/index');
//static file middleware
app.use(express.static(__dirname + '/public'));
app.set('views',__dirname +'/server/views');
app.set('view engine','pug');
app.use('/',serverRoutes);
app.use('/api',api);
//custom error handler
app.use(function(error, req, res, next) {
res.status(error.status || 500);
res.send('Error: '+error.message);
});
app.listen(port);
console.log('Listening on port: '+port);
You've got the whole program listed so there is more than one way for this to have gone wrong. Here are my suggestions to fix this:
Check the version of express-session you've installed. (Just run npm ls in the terminal and in your root Node app folder where you're package.json file is). If it's equal to or greater than v1.5.0, you don't need the cookie-parser for sessions anymore. Comment out the app.use line for the cookie parser and see if this works.
If you still need cookie parser for some other reason, you should use the same secret for sessions and the cookie parser. In your code, you've set two different values for secret.
I've seen that the other big failure for sessions occurs if the session store is not correctly connected to your Node app. Cross-check that the database is available and working. In my experience, Express sessions will fail silently if it can't get to the DB.
Hope this helps.
I'm trying to block certain files in my site from being publicly accessible. For example, if you go to mysite.com/package.json instead of displaying it in the browser i just want to send and error or redirect back to my homepage or something. I feel like this should be easy... but i haven't been able to get anything to work. there isn't anything complicated about the site, and it's running of a fairly simple server.js
var appRoot = __dirname,
express = require('express'),
chalk = require('chalk'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
path = require('path'),
errorhandler = require('errorhandler'),
os = require('os'),
http = require('http'),
Routes;
// -----------------------------
// Configuration
// -----------------------------
var port, env, logs;
// Switch some vars based on the ENV
if(process.env.NODE_ENV === 'production'){
port = 3000;
env = 'production';
} else {
port = 8080;
env = 'development';
}
// Express Variables
var app = express();
var router = express.Router();
// Use static files in root
app.use(express.static(__dirname));
// API config
app.use(bodyParser.json());
app.use(methodOverride());
app.use(errorhandler({ dumpExceptions: true, showStack: true }));
// Database
mongoose.connect(mydb);
// Routes / API Config
Routes = require(appRoot + '/routes')(app, router, mongoose);
// After all routes don't match ie. refreshing a page, send index.html
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/index-' + env + '.html');
});
app.listen(port);
I was hoping to do something like:
app.get('/package.json', function(){
res.end('Not allowed');
});
or even before i send it the static html index check if they are trying to access a restricted file. Any suggestions, resources etc are welcomed. If you need any more info just ask.
Based on your comment
You should replace this line:
app.use(express.static(__dirname ));
with this:
app.use('/assets', express.static(__dirname + '/assets'));
app.use('/views', express.static(__dirname + '/views'));
I am developing an application using the MEAN stack (Node.js, Express, AngularJS, and Mongoose). I have a basic understanding of the two. My API is running on a different port from my frontend, and because of this, I've included the CORS header in my API file. However, Chrome is still giving me this error:
XMLHttpRequest cannot load http://localhost:9000/#/.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is the header I've included in my API:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I have no idea where I'm going wrong. If it helps at all, I'm trying to load a user object in order to display information on a profile page. This is the code from my Profile Controller:
angular.module('angTestApp')
.controller('ProfileCtrl', function ($scope, $http) {
$http.get('http://localhost:8080/profile')
.success(function (user) {
$scope.user = user;
console.log(user);
});
});
EDIT
Here's my server.js file if that helps:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var cors = require('cors');
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://test:test#novus.modulusmongo.net:27017/a3pemoGa')
var classroom = require('./app/models/classroom');
var article = require('./app/models/article');
var user = require('./app/models/user');
//From Tutorial
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());
app.use(cors());
//app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
//From tutorial
// set up our express application
require('./app/config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/API/routes')(app, passport);
//require('./app/API/general');
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
//exports = module.exports = app;
i resolved the cors issue with tricky solution . first create the the route of scrape like this with require "REQUEST" npm
app.get('/scrape', function (req, res) {
console.log("=============================Scrape =========================")
var url = req.body.url;
request(url, function(error, response, html){
if(!error){
res.send(html)
}
});
and in the frontend use like this
$http.get("/scrape", {
params: { "url": "http://localhost:8080/profile" }
});