我正在 AppEngine 上设置一个简单的 Web 应用程序,但在配置 app.yaml 时遇到一些问题。它包括一个 HTML 页面、一个 JS 脚本和一个 NodeJS 服务器。
我的项目结构:
\app.yaml
\package.json
\www
\index.html
\js
\server.js
\index.js
index.html:
<!DOCTYPE html>
<html>
<body>
<div id="JShere" >Hello World !</div>
<div id="ReqAnswer"></div>
</body>
<script src="js/index"></script>
</html>
index.js:
document.getElementById('JShere').innerHTML = "JS is running";
var xhr = new XMLHttpRequest();
xhr.open('GET', "/srv", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('ReqAnswer').innerHTML = xhr.responseText;
}
}
node.js 服务器:
const express = require('express');
const app = express();
app.get('/srv', function (req, res) {
res.send('Request anwser')
})
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
package.json:
...
"scripts": {
"start": "node www/js/server.js",
"test": "mocha --exit test/*.test.js"
},
...
app.yaml:
runtime: nodejs10
handlers:
- url: /
static_files: www/index.html
upload: www/index.html
- url: /index
static_files: www/index.html
upload: www/index.html
- url: /page2
static_files: www/page2.html
upload: www/page2.html
- url: /www
static_dir: www
当我在本地检查时,index.js正确修改了index.html,但是当我将其部署到App Engine时,index.js是被阻止(MIME 类型(“text/html”))。然后它“无法加载”index.html。尽管如此,脚本仍然向服务器发起 GET 请求并收到 404 错误。 是 App.yaml 问题还是其他问题?
最佳答案
仔细检查 GAE 日志条目,了解所请求的确切 URL(并以 404 拒绝)。这通常需要与静态处理程序之一的 url
相匹配。图案。如果发生匹配,则由相应处理程序的 static_file
指定的文件/static_dir
和upload
规范(相对于应用程序的顶级目录 - app.yaml 文件所在的位置)应该发生。
假设初始请求是 /
。这与您的第一个静态处理程序相匹配,因此您的 www/index.html
将被送达。
但是index.html
文件引用 js/index
脚本内,因此另一个请求将跟随该 URL。但是该 URL 与您的任何处理程序的模式都不匹配,因此它将得到 404。您也没有任何名为 index
的文件。 .
假设在这种情况下您想要提供的服务实际上是 www/js/index.js
文件你必须:
更正
index.html
中的文件名引用文件:<script src="js/index.js"></script>
确保此引用与静态处理程序匹配
url
图案。可能是这样的(对于每个以.js
结尾的请求路径,将尝试提供与该路径匹配但相对于www/js
目录的文件):- url: /(.*\.js)$ static_files: www/js/\1 upload: www/js/.*\.js$
或者,您可以使用可应用于多种类型文件的方案,而不是那些以 .js
结尾的文件。 :
使用
www
引用该文件index.html
中的前缀文件:`<script src="www/js/index.js"></script>`
重复使用最后一个处理程序,但在其
url
中添加通配符确保www
下的所有内容都匹配(因为www/blah
与www
模式不匹配):`- url: /www/*`
也可以在没有 .js
的情况下引用脚本后缀,但是您需要一个专门针对该文件的处理程序 - 将其映射到实际的文件名,您不能使用通配符。所以我不推荐这样做,因为它很快就会变得非常复杂。
您必须类似地考虑需要提供服务的所有其他静态元素。
关于javascript - 如何使用 JS 和 NodeJS 服务器为标准 html 页面正确配置 app.yaml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724252/