[英]using AngularJS html5mode with nodeJS and Express
我正在使用帶有Express的nodeJS服務器來為我的AngularJS應用程序提供服務。 當我使用angularJS默認路由(hashbangs)時,這一切都正常,但現在我正在嘗試激活html5模式。
我正在激活html5mode,如下所示:
$locationProvider.html5Mode(true).hashPrefix('!');
這就是我的nodeJS app.js
文件的樣子:
var path = require('path'),
express = require('express'),
app = express(),
routes = require(path.join(__dirname, 'routes'));
app.configure(function() {
app.use(express.logger('dev'));
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.all("/*", function(req, res, next) {
res.sendfile("index.html", { root: __dirname + "/../app" });
});
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
但是,這現在作為我的index.html
文件提供所有請求,因此我從requireJS收到以下錯誤:
Uncaught SyntaxError: Unexpected token <
我嘗試將以下內容添加到我的nodeJS app.js
以便它可以正確地提供我的資源:
app.use("/js", express.static(__dirname + "/../app/js"));
app.use("/img", express.static(__dirname + "/../app/img"));
app.use("/css", express.static(__dirname + "/../app/css"));
app.use("/partials", express.static(__dirname + "/../app/partials"));
但仍然沒有運氣。
我還嘗試用以下app.all
替換app.all
語句:
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/../app/index.html');
});
但那也不起作用。 我怎么做才能讓angularJS html5mode與nodeJS和Express一起工作? 謝謝。
您的初始修復(聲明特定前綴的靜態中間件處理程序)應該可以正常工作,但您需要確保它們在任何其他路由之前聲明(和app.router
,盡管您不需要顯式使用它):
// these need to go first:
app.use("/js", express.static(__dirname + "/../app/js"));
app.use("/img", express.static(__dirname + "/../app/img"));
app.use("/css", express.static(__dirname + "/../app/css"));
app.use("/partials", express.static(__dirname + "/../app/partials"));
// any other routes:
app.all("/*", ...);
此外,您需要確保實際上聲明了前綴靜態處理程序正常(正確路徑),否則它們將無法找到任何請求的文件,並且請求將通過中間件鏈傳遞並最終由捕獲程序處理 - 所有處理程序(應該很容易通過注釋掉catch-all處理程序來測試,看看是否有任何JS / CSS / ...請求正常工作)。
配置express 4服務器如:
app.use(express.static(__dirname + '/public'));
app.get('/*', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
和角度像:
app.config(function($stateProvider, $urlRouterProvider, $locationProvider){
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/main.html'
})
.state('register', {
url: '/register',
templateUrl: 'templates/register.html'
});
$urlRouterProvider.otherwise("/");
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
我正在使用客戶端上的Angularjs和Requirejs處理Web應用程序,並在服務器上使用Nodejs。
下面是一些示例代碼,向您展示我如何設置它。
請注意,此示例顯示了一個哈希URL,但您可以通過修改中間件功能和角度配置輕松更改它
isXHR: function (req, res, next) {
if (req.xhr || req.get("angular-request") === "ajaxRequest") {
next();
} else {
var url = req.url;
var urls = url.split("/");
var last = _.last(urls);
urls = _.without(urls, last);
url = urls.join("/") + "#/" + last //remove the hash if you want to make it html5mode;
res.redirect(url);
}
}
//I'm using express-namespace to group my routes
app.namespace("/requirements", function(){
//Shared local variable used across the application
var info = {
app: {
title: "Requirements",
module: "app/requirements" // where the angular application stored
}
}
//this is the main url that will user request
Route.get("/", function (req, res) {
res.cookie("profileRegisterationSteps", 0);
res.render("app/requirements/index", info);
});
//this is the url angular js will request
Route.get("type", filters.isXHR, function (req, res) {
res.render("app/requirements/profile/type", info);
});
})
require(['App', 'underscore', 'ngAmd'/*angular amd*/, 'autoload'/*No Sense*/, 'appLoader' /*i used to load my scripts file for the route user requested (not all scripts files only who requested) before template laoded*/, 'appRoute'/*this is a list of routes*/], function (app, _, amd, autoload, loader, routes) {
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
//remove a clearn URL
$locationProvider.html5Mode(false);
//ku dar header kan si uu server ka u ogaado Request in yahay Ajax
$httpProvider.defaults.headers.common['angular-request'] = "ajaxRequest";
//Route Config
var Route = $routeProvider;
//get all routes objects that defined in routes module
_.each(routes, function (route) {
// extend the routes module objects and use its properties
Route.when(route.url, _.extend(route, {
//call returning function in loader module and write the promise
resolve: _.extend(loader(route))
}));
});
Route.otherwise({
redirectTo: "/"
});
});
//start the application
amd.bootstrap(app);
});
require.config({
paths: {
//pages
type: "Apps/requirements/pages/type"
}
});
define(['App'], function(app) {
return function (options) {
return {
loader: function ($q, $rootScope) {
var defer = $q.defer();
var module = options.name// the name of the route (this name corresponds to the requirejs module name above;
if (!!(module)) {
if (require.defined(module)) {
defer.resolve();
} else {
require([module], function () {
$rootScope.safeApply(function () {
defer.resolve();
})
});
}
} else {
defer.resolve();
}
return defer.promise;
}
}
}
});
define(function(){
return {
{
name : "type",
url : "/",
templateUrl : "/requirements/type",
view : 'services'
}
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.