【问题标题】:unable to get a response from the express nodejs server when being directed to a html page被定向到 html 页面时无法从 express nodejs 服务器获得响应
【发布时间】:2018-02-22 16:13:50
【问题描述】:

单击 public/index.html 中的按钮时,我被定向到 game.html,但它没有显示任何响应。它说This site can’t provide a secure connection: localhost sent an invalid response. 当我转到 localhost:3000 并单击按钮后,我被引导到 game.html,但服务器没有加载该页面。

public/index.html

<!-- HTML -->
<button class="w3-button w3-hover-black"> </button>

<!-- JavaScript -->   
<script>
  var buttons=  document.getElementsByClassName('w3-button w3-hover-black');
  for(i=0;i<buttons.length;i++){
    buttons[i].onclick = function(){
    window.location.href = "http://localhost:3000/game.html";
   }
 }
</script>

public/game.html

 <div id = "gameDiv"></div>
 <script src = "/socket.io/socket.io.js"></script>
 <script src = "lib/phaser.min.js"></script>
 <script src = "main.js"></script>
 <script src = "player.js"></script>   

服务器/server.js

var app = express();
const port = process.env.PORT ||3000 ;
const pathjoin = path.join(__dirname, '../public'); 
const pathjoin1 = path.join(__dirname,'../public/game.html');
var server = http.createServer(app);

app.use(express.static(pathjoin));

app.get('/game.html',(req,res)=>{
  res.sendFile(pathjoin1);
});

var io = socketIo(server);

io.on('connection',(socket)=>{
  console.log('user connected ' + socket.id);
});

【问题讨论】:

  • 你是想在去/game的时候下载html文件,还是想渲染成html?
  • 渲染成html

标签: javascript html node.js express


【解决方案1】:

你想要的是 res.render:some docs

一个例子:

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

app.get('/game.html',(req, res) => {
  res.render('game.html');
});

【讨论】:

  • 但是你能告诉我为什么 res.render 和 res.sendFile 之间的区别以及我们为什么使用 res.render 而不是 res.sendFile 吗?
  • sendFile Transfers the file at the given path,作为渲染 Renders a view and sends the rendered HTML string to the client。换句话说,当您使用 sendFile 时,它​​会尝试下载文件而不是在浏览器窗口中显示它。以下是对这些报价的引用:expressjs.com/en/4x/api.html#res.sendFile & expressjs.com/en/4x/api.html#res.render
  • 是的。 .我在你的回复和我的问题之间的 6 分钟内用谷歌搜索了它!:) 非常感谢瑞克!顺便说一句,为什么我们不像 app.use() 那样在 res.render() 中指定文件路径?服务器如何知道文件 game.html/
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 2017-06-25
相关资源
最近更新 更多