首页 > 解决方案 > 如何修复错误无法使用 Node.js / Express 获取

问题描述

我有一个类服务器:Server.js

const express = require('express');

class Server {
    constructor() {
        this.app = express();

        this.app.get('/', function(req, res) {
            res.send('Hello World');
        })
    }

    start() {
        this.app.listen(8080, function() {
            console.log('MPS application is listening on port 8080 !')
        });
    }
}
module.exports = Server;

我在 app.js 中启动我的服务器:

const Server = require('./server/Server');
const express = require('express');

const server = new Server();

server.start();

server.app.use('/client', express.static(__dirname + '/client'));

我的html代码:index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <title></title>
</head>
<body>

    <div id="historique">
        <button v-on:click="openHistorique">
            Historique Proface
        </button>
    </div>
</body>
</html>

我的 index.js :

window.onload = function () {   
    var hist = new Vue({
        el:'#historique',
        methods: {
            openHistorique: function() {
                console.log("On clique");
                document.location.href="../AffichageHistorique/index.php";
            }
        }
    })
}

和文件夹结构:

client
  AffichageHistorique
    index.php
  js
    index.js
  index.html
server
  Server.js
app.js

当我单击 index.html 中的按钮时,我想打开 index.php,但我遇到了错误Cannot GET /AffichageHistorique/index.php,我不知道如何解决这个问题。

标签: javascriptnode.jsexpress

解决方案


这里:

this.app.get('/', function(req, res) {

…您为客户端尝试获取时发生的情况编写了一个处理程序/

你还没有为/AffichageHistorique/index.php.

server.app.use('/client', express.static(__dirname + '/client'));

… 接近,但由于您的 URL 不以 开头/client,因此不会被击中。

即使这样做,它也不会执行PHP。

static 模块用于提供静态文件,而不是用于执行 PHP。

如果您使用的是 PHP,请考虑使用 PHP 设计的服务器(如 Apache HTTPD 或 Lighttpd)。


推荐阅读