无法使用express加载静态文件

时间:2013-12-13 15:45:43

标签: javascript node.js express

她是我的app.js,是express.js的备用文件

<

var express = require('express')
  , argv = require("optimist").argv
  , fs = require("fs")
  , hbs = require("hbs")
  , WatsonClient = require("watson-js");


var clientId        = argv.key || '5b1cb9a9c097e1100eeeebaf66117265'
  , clientSecret    = argv.secret || '01b8417ac6872450'
  , appPort         = argv.port || '3000';


function cp(source, destination, callback) {

    // Read a buffer from `source`
    fs.readFile(source, function(err, buf) {
        if (err) { return callback(err); }

        // Write that buffer to the new file `destination`
        fs.writeFile(destination, buf, callback);
    })
}


var Watson = new WatsonClient.Watson({ client_id: clientId, client_secret: clientSecret });


var app = express();


app.configure(function() {
    console.log('inside function');
    // Set the location of views and type of view engine
    app.set('views',__dirname + '/app/views');
        console.log(__dirname + '/app/views');
    app.set('view engine', 'html');
    app.engine('html', require('hbs').__express);
       console.log('after view');

    // Set up a standard Express configuration
    app.use(express.logger());
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({
        secret: "This is an example."
    }));
    app.use(app.router);
    console.log('before public');
    // Set the location of static assets
    app.use(express.static(__dirname+'/public'));
        console.log(__dirname+'/public');
        console.log('after public');

});


app.get('/', function(req, res) {
    res.render('layout');
});


app.post('/upload', function(req, res) {


    cp(req.files.upload_file.filename.path, __dirname + req.files.upload_file.filename.name, function() {


        res.send({ saved: 'saved' });
    });
});

app.post('/speechToText', function(req, res) {

    // Traditionally, you would store this access token somewhere safe like a database. For the purposes of this example, we're going to generate a new one on the first request and store it in the session so we don't have to deal with a database or tracking expiry and refreshing access tokens.
    if(!req.session.accessToken) {

        // !AT&T API: Get Access Token
        Watson.getAccessToken(function(err, accessToken) {
            if(err) {
                // Handle an error getting an access token
                res.send(err);
                return;
            } else {
                req.session.accessToken = accessToken;

                token.
                Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
                    if(err) {

                        res.send(err);
                        return;
                    }

                    res.send(reply);
                    return;
                });
            }
        });
    } else {

        Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
            if(err) {

                res.send(err);
                return;
            }

            return;
        });
    }
});


app.listen(appPort);
console.log('AT&T Speech API Basic Walkthrough App started on Port ' + appPort + '.');

//!USAGE:node app.js --key = --secret = --port =

//!SETUP:依赖关系 / *  * Express:最小的Web应用程序框架  * FS:Node.js文件系统模块  *乐观主义者:轻量级选项解析  * HBS:Handlebars的Express View Engine包装器  * Watson.js:AT& T Speech API的简单API包装器  * /

我的layout.html是

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>AT&amp;T Speech API Example: Basic Walkthrough</title>
    <meta name="description" content="Application for the AT&T Speech API Deep Dive Presentation at DevLab 2012">
    <meta name="author" content="Michael Owens">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="public/styles/bootstrap.css">
    <link rel="stylesheet" href="public/styles/example-basic.css">
    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js'></script>
</head>
<body>
     <a  onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play">
                                             Play
                                         </a> 
<div class="container">
    <div class="row">
        <div class="span12">

        </div>
    </div>
    <div class="row">
        <div class="span4">
            <h2 id="progress-title">Progress (Step <span id="progress-step">1</span> of 5)</h2>
            <div id="progress-indicator" class="progress progress-striped">
                <div class="bar" style="width: 20%;"></div>
            </div>
            <ol class="progress-list">
                <li id="progress-01" class="active">Access User's Microphone</li>
                <li id="progress-02">Record Audio from Mic</li>
                <li id="progress-03">Save Audio to File</li>
                <li id="progress-04">POST File to AT&amp;T Speech API</li>
                <li id="progress-05">Receive Results from AT&amp;T Speech API</li>
            </ol>
            <div>
                <a href="/" class="btn"><i class="icon-refresh"></i> Start Over</a>
            </div>
        </div>
        <div class="span8">
            <h2>Current Status</h2>
            <div id="status-mic" class="alert alert-info">
                Audio Status: <strong>waiting</strong>
            </div>
            <div id="status-upload" class="alert alert-info">
                File Status: <strong>waiting</strong>
            </div>
            <div id="control_panel">
                <div class="btn-group">
                    <button id="button-connect" class="btn btn-large btn-success"><i class="icon-off icon-white"></i> <span class="action">Connect</span></button>
                    <button id="button-recorder" class="btn btn-large" disabled="disabled"><i class="icon-music"></i> <span class="action">Record</span></button>
                    <span id="button-save" class="btn">
                        <button disabled="disabled" class="btn btn-large"><i class="icon-download-alt"></i> <span class="action">Save</span></button>
                        <span id="save_button"><span id="flashcontent"></span></span>
                    </span>
                    <button id="button-transcribe" class="btn btn-large" disabled="disabled"><i class="icon-share-alt"></i> <span class="action">Transcribe</span></button>

                </div>
            </div>
            <div id="transcribe-container">
                <h2>Speech API Response</h2>
                <div id="transcribe-response"></div>
            </div>
        </div>

    </div>
    <form id="uploadForm" name="uploadForm" action="/upload" >
        <input name="authenticity_token" value="xxxxx" type="hidden">
        <input name="upload_file[parent_id]" value="1" type="hidden">
        <input name="format" value="json" type="hidden">
    </form>
    <script type="text/javascript" src="public/scripts/swfobject.js"></script>
    <script type="text/javascript" src="public/scripts/example-basic.js"></script>




</div>


</body>
</html>

当我在cmd中的节点上运行app.js时,它给出了我无法加载静态文件的错误,即js和css文件,但它加载了视图部分,即layout.html

确切的错误是

&LT;

获取h:// ip:3000 / public / scripts / swfobject.js 404(未找到)

获取h:// ip:3000 / public / scripts / example-basic.js 404(未找到)

获取h:// ip:3000 / public / styles / bootstrap.css 404(未找到)

获取h:// ip:3000 / public / styles / example-basic.css 404(未找到)

&GT;

ip -localhost h -https

我的foldr结构是

示例(父文件夹)

子文件夹

app / views / layout.html(代码在上面给出)

public / scripts / js文件

public / styles / css文件

app.js(上面给出了代码)

所有上述子文件夹(app,public,app.js)处于同一级别

所以请给我一些建议

1 个答案:

答案 0 :(得分:2)

如果您从网址中删除“公开”,它应该有效,例如:

<link rel="stylesheet" href="/styles/bootstrap.css">
<link rel="stylesheet" href="/styles/example-basic.css">

您将静态目录设置为/public,以便在其中查找静态资源。你这样做了:

app.use(express.static(__dirname+'/public'));

当您向这些网址添加public时,它会在/public中查找名为public的文件夹,该文件夹无法找到。但是,它会找到一个名为styles的文件夹。