I'm using the following (server.js) to create a node http server to load an Angular page (index.html).
server.js
var http = require('http');
var fs = require('fs');
var HOST = '127.0.0.1';
var PORT = 3000;
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
response.end(fs.readFileSync('index.html'));
}).listen(PORT, HOST);
console.log('Node server listening at http://' + HOST + ':' + PORT);
index.html
<html lang="en" ng-app="planetApp">
<head>
<meta charset="utf-8" />
<title>Planet App</title>
<!-- Include external styles -->
<link rel="stylesheet" href="css/styles.css" />
<!-- Include external Angular Libs -->
<script src="js/lib/angular.min.js"></script>
<script src="js/lib/angular-route.min.js"></script>
<!-- Include external custom JS files -->
<script src="js/planetController.js"></script>
<script src="js/planetFactory.js"></script>
<script src="js/planetDirective.js"></script>
<script src="js/planetApp.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
The App loads fine if I serve it from WAMP, but I get the following error when I serve it from node:
SyntaxError: expected expression, got '<'
<html lang="en" ng-app="planetApp">
I think it may have something to do with the templateURL(s) in the following:
planetApp.js
var planetApp = angular.module('planetApp', [
'ngRoute',
'planetController',
'planetFactory',
'planetDirective'
]);
// App Config - runs once to register controllers
planetApp.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '../templates/planet_list.html',
controller: 'PlanetListCtrl'
}).
when('/:planetId', {
templateUrl: '../templates/planet_detail.html',
controller: 'PlanetDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
});
Does anyone know how this can be resolved, using node's http server (not express)?
Thanks for any guidance!
Solved with the following:
server.js
var http = require('http');
var fs = require('fs');
var HOST = '127.0.0.1';
var PORT = 3000;
http.createServer(function (request, response) {
var url = request.url;
url = url.substring(1, url.length);
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
response.end(fs.readFileSync(url));
}).listen(PORT, HOST);
console.log('Node server listening at http://' + HOST + ':' + PORT);
Related
I am trying to sign up the user but I am getting an error back from the server.
VM19:1 POST http://localhost:5001/auth/undefined/auth/signup 404 (Not Found)
//
err: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /auth/undefined/auth/signup</pre>
</body>
</html>
My server settings are below:
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {});
And cors:
app.use(
cors({
credentials: true,
origin: process.env.ORIGIN || "http://localhost:5001",
})
);
On the front end my function looks like this:
const authService = axios.create({
baseURL: `${process.env.SERVER_URL}/auth`,
});
export function signup(credentials) {
return authService
.post("/signup", credentials)
.then(successStatus)
.catch(internalServerError);
}
I don't know whether the issue is related to routing? Also when I set the port for the front end ORIGIN to 3000 it's says that the application is running on this port although it is running on port 5000.
Thanks
I'm building a MVC Express app using React and node.js .
i have index.html in public folder , and index.jsx in the views folder
then, I start my server, go to localhost and I see a blank page, i tried many solutions and none of them solve the problem
this is file structure
+-- app.js
+-- public
| +-- index.html
+-- routes
| +-- index.js
+-- views
| +-- index.jsx
this is the app.js in the root
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/public'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
and this is public/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js" type="text/javascript"></script>
<title>MERN</title>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="root"></div>
<script type="text/javascript" ></script>
</body>
</html>
and views/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>hello express</h1>,document.getElementById('root')
);
routers/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express'}); this is the old line
res.render('index.html');
});
module.exports = router;
Try using sendFile instead of render in your routers/index.js file
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express'}); this is the old line
res.sendFile('index.html');
});
module.exports = router;
I have configure node js default project with express and using HTML page instead of JADE. I want to use Angular JS within HTML pages. Angular JS Simple examples are working fine in this project as :
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Its working Fine. But if i am using {{name}} instead of ng-bind="name", its not working in this project.
For Example:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
This is not working in node project. Can anyone help me to find-out the issue.
App.js File code is as following:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Sql server new code
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var webconfig = {
user: 'sa',
password: '#####',
server: '######',
database: 'Test_Training',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
var sql = require('mssql');
// Sql server new code
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// To use simple html page
var cons = require('consolidate');
// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// To use simple html page
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/public'));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Help will be appreciated.
The html engine is not supported out of the box.
(ref: https://github.com/expressjs/express/wiki#template-engines)
Solution given by #Thanh Tùng will work, but if you really want to set html as a view engine you should follow this solution
app.set('views', path.join(__dirname, 'views'));
// Set EJS View Engine
app.set('view engine','html');
// Set HTML engine
app.engine('html', require('ejs').renderFile);
Later you need to place your index.html inside /views directory
(original answer: https://stackoverflow.com/a/44945104/3627827)
EDIT: updated answer as suggested by #DanielZiga
First remove it :
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
I'm not sure about your strug folder but I guess file index.html of you in folder public . Try add this code in your node :
app.get('/*',function(req,res){
res.sendFile( index.html,{root:path.join(__dirname,public/index.html)});
})
You are using Swig as a Template Engine for your Server Side Rendering.
As you can see in its doc, Swig uses {{ and }} as interpolation delimiters... they're the same used by AngularJS.
What could happen is that Swig doesn't let your raw html reach the angular...
Try to change interpolation delimiters:
// https://docs.angularjs.org/api/ng/provider/$interpolateProvider
angular
.module('ModuleName')
.config(['$interpolateProvider', function($interpolateProvider) {
// set start symbol here
$interpolateProvider.startSymbol('^_^');
// set end symbol here
$interpolateProvider.endSymbol('"_"');
}])
;
I am doing a tutorial trying to learn Node and Angular. I am completely new to this, I come from a LAMP stack environment so it's a whole new world to me and I feel completely lost.
I have installed Angular JS and included it in my HTML file but I keep getting this error
http://localhost:3000/node_modules/angular/angular.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/app/app.js Failed to load resource: the server responded with a status of 404 (Not Found)
EDIT: I have tried some different approached but they're all pointing to the /server/ directory.
var appDir = path.dirname(require.main.filename);
var appDir = path.dirname(process.mainModule.filename);
Both of these point to /server/ directory.
My folders structure is as follows:
/app
app.js
/node_modules
/server
server.js
index.html
This is server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost:27017/social');
app.use('/app', express.static(__dirname + '/app'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.get('/', function(req, res) {
res.sendFile("index.html", {root: '../'});
});
app.listen('3000', function() {
console.log('Listening for localhost 3000');
});
This is app.js
(function() {
angular.module('Social', []);
}());
This is index.html
<!DOCTYPE html>
<html lang="en" ng-app="Social">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
<p>Testing the test</p>
</body>
<script src="node_modules/angular/angular.min.js"></script>
<script src="app/app.js"></script>
</html>
__dirname is "The name of the directory that the currently executing script resides in." which is the directory server.js is in.
So when you are doing:
express.static(__dirname + '/app')
I think it is actually looking for /server/app which is not correct.
I'm following the "MEAN Machine" book and I'm trying to set up a Angular with Express but I keep running into this error when I'm calling Angular.min.js:
"Uncaught SyntaxError: Unexpected token <"
I've been searching around for an hour or so now and haven't been able to fix it.
Folder Structure
Here's my Express Code:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
cors = require('cors'),
path = require('path'),
config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(morgan('dev'));
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/index.html'));
});
app.listen(config.devPort);
console.log('Running on ' + config.devPort);
And here's where my index.html where Angular is being called:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<base href="/">
</head>
<body ng-app="sample">
<h1>Welcome to the homepage!</h1>
<div ng-controller="ScheduleCtrl as schedule">
<h1 ng-bind="schedule.test"></h1>
</div>
<!-- inject:js -->
<script src="/public/assets/lib/angular/angular.min.js"></script>
<script src="/public/app/app.js"></script>
<script src="/public/app/modules/schedule/schedule.controller.js"></script>
<!-- endinject -->
</body>
</html>
Here's the app.js file:
(function() {
'use strict';
angular
.module('sample', []);
})();
Here's the schedule.controller.js file:
(function() {
'use strict';
angular
.module('sample'),
.controller('ScheduleCtrl', ScheduleCtrl);
ScheduleCtrl.$inject = [];
function ScheduleCtrl() {
var vm = this;
vm.test = "Hello World!";
};
})();
EDIT:
I checked my console and the paths for the files are giving me a 304:
GET / 304 1.934 ms - -
GET /public/assets/lib/angular/angular.min.js 304 2.262 ms - -
GET /public/app/app.js 304 2.578 ms - -
GET /public/app/modules/schedule/schedule.controller.js 304 2.855 ms - -
Try to put the scripts in head tag instead of body tag (or before body tag), you're using AngularJS syntax (ng-app, etc.) before the script is included
This could be the error:
angular
.module('sample'), <-- this comma should not be here
.controller('ScheduleCtrl', ScheduleCtrl);