******************************
PARA EL SERVIDOR WEB
cd proj
mkdir web1
cd web1
npm init (crea el archivo package.json. Si se indica --yes, no pide ningun dato, asume los default)
cuando pregunte el nombre del main, en lugar de index ponerle app
npm install express --save
npm install method-override --save
npm install body-parser --save
crear un archivo app.js y agregarle este codigo:
(observar que se agrega el access control allow origin para que
se puedan hacer requests desde localhost:4200)
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override");
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello World!");
});
router.get('/prueba', function(req, res) {
var p = [{nombre: 'carlos', apellido: 'russo'},
{nombre: 'karina', apellido: 'ortiz'}];
res.send(p);
});
app.use(router);
app.listen(8080, function() {
console.log("Node server running on http://localhost:8080");
});
luego, ejecutar:
node app.js
y queda corriendo el servidor web.
para que no haya que reiniciarlo cada vez que se hace un cambio, instalar nodemon:
npm install -g nodemon
luego iniciar la aplicacion con nodemon app.js, o simplemente nodemon (ya sabe que es app.js
porque se lo indicamos en el ng init)
para probarlo, ir a http://localhost8080
o a http://localhost:8080/prueba
***********************************
No hay comentarios:
Publicar un comentario