Problems with res.sendFile () express 4.14 Node.js 4.2

0

Good morning. I've been wrong for a couple of days. I'll let you know in case someone knows why it happens.

I have a project AngularJS v1.5.11 + Node.js v4.2.6 (with express v4.14.1 ) and when I raise it with node server.js Angular does not recognize me.

However when I run it without the Node.js (dragging it to the browser) it works correctly for me. That's why I've come to the conclusion that the error is in the Express.

My folder system is this ::

  • server.js
  • node_modules /
  • public /
  • --- app /
  • --- assets /
  • --- index.html
  

Server.js Code (updated)

var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORT||4000;

app.use(express.static(path.join(__dirname, 'assets')));
app.get('*', function (req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

app.listen(port, function () {
  console.log('Example app listening on port 3000!');
});
  

Code index.html

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>Index</title>
    <script src="../server.js"></script>
    <script src="app/libs/angular.js"></script>
    <script src="app/libs/angular-route.js"></script>

    <script src="app/js/app.js"></script>
    <script src="app/js/config.js"></script>

    <script src="app/js/components/testText/test-text.module.js"></script>
    <script src="app/js/components/testText/test-text.component.js"></script>
    <script src="app/js/components/testText/test-text.template.html"></script>
  </head>
  <body >

    <div ng-view></div>
    hola

  </body>
</html>

If anyone knows what I can do. Please do not hesitate to comment.

    
asked by PictorGames 08.02.2017 в 17:51
source

1 answer

3

So that express can send static files you must establish the directory that contain those files. This is done through a middleware as I indicate below:

app.use(express.static(path.join(__dirname, 'public/app')));

The previous line tells express that everything in public/app are static files. In your HTML, you should only ask for them through relative routes, where / equals the static directory:

<script src="/server.js"></script>
<script src="/libs/angular.js"></script>
<script src="/libs/angular-route.js"></script>

<script src="/js/app.js"></script>
<script src="/js/config.js"></script>

<script src="/js/components/testText/test-text.module.js"></script>
<script src="/js/components/testText/test-text.component.js"></script>
<script src="/js/components/testText/test-text.template.html"></script>
    
answered by 08.02.2017 / 20:13
source