AnguarJS + node.js (web-server.js) remove hashtag from url and support it by server side

淺唱寂寞╮ 提交于 2019-12-23 05:06:15

问题


As far as i understand in order to remove the hashtag from angularJS i need to add the following code:

config(function($locationProvider) {
    $locationProvider.html5Mode(true);
}).

after added this code, i get 404 from my simple server (web-server.js) which is the same simple server provided with angular tuotorial.

From the stackoverflow i found 2 links that helped me to understand that i need to add routing to my server in order to support this operation.

AngularJs Routing without hashtag in link?

routing and clean path (no hashtag) not working in angularJS

well i didn't understand how to add web-server.js the routing i needed

my link was previously was: /app/index.html/#cars and now he is /app/index.html/car

how should i changed web-server.js in order to fit my new routing needs?

thanks.


回答1:


The simlpiest and the fastest way to set up node server with routing is to use Express framework.

With Express very simple skeleton of your webapp would look like this:

var http = require('http');
var express = require('express');

var app = express();

app.configure(function() {
    app.set('views', __dirname + '/app');
    app.set('view engine', 'ejs');       //EJS template engine (no HTML for now)
    app.use('/public', express.static(__dirname + '/public'));  //specify path to your static files
});

//"car", "bus", and "van" are the pages of your app
app.get('/:page(|car|bus|van)', function(req, res) {
    res.render('index', {
        page: req.params.page     //pass page to the view (just in case)
    });
});

http.createServer(app).listen(80);

Then you will have to create /app/index.ejs file which is in fact the html file with some additioal features.

Thus, when you navigate in your browser to /car, /bus, or /van you will see the content of index.ejs file.

Hope this helps!

Edit

I've just corrected /:page(|car|bus|van) part. Please try the last version

Edit 2

Oh, I forgot to say, you have to npm install ejs from command line to start using EJS templates



来源:https://stackoverflow.com/questions/21660454/anguarjs-node-js-web-server-js-remove-hashtag-from-url-and-support-it-by-ser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!