Node JS 获取文件路径

刚开始使用server的模块,自己在项目工程中新建了一个文件夹,里面放了一个html文件,想要在浏览器访问这个html,就要写一个路径,应该使用如下方法:

app.get('/index.html', function (req, res) {
    res.sendFile( "C:/Users/ALLONE/WebstormProjects/untitled1/View_layout/index.html" );//绝对路径
    res.sendFile(path.join(__dirname,'/View_layout/index.html') );//使用path的方式,获取动态的路径
})
  完整代码如下:

var express = require('express');
var path = require('path');
var app = express();

app.use(express.static('public'));

app.get('/index.html', function (req, res) {
    res.sendFile( "C:/Users/ALLONE/WebstormProjects/untitled1/View_layout/index.html" );
    res.sendFile(path.join(__dirname,'/View_layout/index.html') );
})

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

    // 输出 JSON 格式
    var response = {
        "first_name":req.query.first_name,
        "last_name":req.query.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response));
})

var server = app.listen(8081, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例,访问地址为 http://%s:%s", host, port)

})
记录一下,防止忘了


你可能感兴趣的:(前端)