节点JS和AngularJS - 脚本和链接未找到 - 404
我试图用Openshift 2构建Node.js/AngularJS应用程序。服务器正在成功运行,如果我去本地地址,我得到index.html(但空白,因为它不加载CSS),我无法获得index.html上的脚本和链接,我得到一个错误404,但我不知道为什么。节点JS和AngularJS - 脚本和链接未找到 - 404
文件夹结构:
sw [sw master]
pages
index.html
inicio.html
css
inicio.css
js
angular.js
aplicacion.js
app.js
start.js
app.js
const http = require('http'),
fs = require('fs'),
path = require('path'),
contentTypes = require('./utils/content-types'),
sysInfo = require('./utils/sys-info'),
env = process.env;
let server = http.createServer(function (req, res) {
let url = req.url;
if (url == '/') {
url += '/index.html';
}
// IMPORTANT: Your application HAS to respond to GET /health with status 200
// for OpenShift health monitoring
if (url == '/health') {
res.writeHead(200);
res.end();
} else if (url == '/info/gen' || url == '/info/poll') {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache, no-store');
res.end(JSON.stringify(sysInfo[url.slice(6)]()));
} else {
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
} else {
let ext = path.extname(url).slice(1);
if (contentTypes[ext]) {
res.setHeader('Content-Type', contentTypes[ext]);
}
if (ext === 'html') {
res.setHeader('Cache-Control', 'no-cache, no-store');
}
res.end(data);
}
});
}
});
server.listen(env.NODE_PORT || 3000, env.NODE_IP || 'localhost', function() {
console.log(`Application worker ${process.pid} started...`);
});
的index.html
<!DOCTYPE html>
<html lang="es" data-ng-app="TFG">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Página principal</title>
<script src="../js/angular.js"></script>
<script src="../js/app.js"></script>
<link href="../css/inicio.css" rel="stylesheet" />
</head>
<body>
<!--CUERPO-->
<div data-ng-view></div>
</body>
</html>
Node.js的SCRI运行服务器的pt将从页面文件夹中呈现html。此index.html中的css和js通过文件夹结构的相对路径链接,但您也需要公开公开,以便在浏览器尝试获取资源时将其公开。您将需要一些代码来提供该静态内容。
事实上,您自己的代码将404返回为浏览器试图从您的网页文件夹获取资源(css和js)并且找不到它们的URL。
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
}
你应该包括一些代码,返回的CSS和JS文件。
当您在nodejs文件中提供路径时,您的索引文件应该位于根级别。 现在你的index.html位于“pages”文件夹下。 页 的index.html inicio.html
我认为这将是你的树
SW [SW大师] 页 inicio.html CSS inicio.css JS angular.js aplicacion .js文件 强调文本的index.html
app.js start.js
我认为这是Openshift在创建应用程序时给我的:https://github.com/icflorescu/openshift-cartridge-nodejs/ tree/master/usr/template –
必须遵循那些他们也提供描述的github链接。 –
否则,您必须从服务器发送css,js的路径。 –
你如何在本地主机上运行你的服务器?你提到的是哪个本地地址? – navjotdhanawat
我在127.0.0.1:3000上运行应用程序like node.js应用程序 –