简体   繁体   English

未定义node.js-> res.sendFile()

[英]node.js -> res.sendFile() is not defined

So I am using node.js with mySQL. 所以我在mySQL中使用node.js。 When I start the server, everything is ok, but when I access 127.0.0.1:3000, it says res.sendFile() is not defined. 当我启动服务器时,一切正常,但是当我访问127.0.0.1:3000时,它说未定义res.sendFile()。 I want to send the index html file as a response from the server but it doesn't work. 我想从服务器发送索引HTML文件作为响应,但是它不起作用。 What is the problem? 问题是什么?

var app = require('express')();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var db = mysql.createConnection({
    host : "127.0.0.1",
    user : "root",
    password : "",
    database : "user_data",
    port : 3306
});

db.connect();

app.get('/',function(req, res){
  res.sendFile(__dirname+'/index.html');
});
app.listen(3000);

Depending on your version, that feature(function) is not provisioned. 根据您的版本,未配置该功能。

Sanitize your packages, first change express version to 4.15.2 then, delete your node_modules folder. 清理软件包,首先将Express版本更改为4.15.2然后删除您的node_modules文件夹。 Then npm install . 然后npm install

You should enable static file serving. 您应该启用静态文件服务。

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

Then after words you can thus use res.reder('index'); 然后,在单词之后,您可以使用res.reder('index'); Though you must set the view engine first.Here is little more information. 尽管您必须先设置视图引擎。以下是更多信息。

app.render(view) app.render(视图)

Returns the rendered HTML of a view via the callback function. 通过回调函数返回视图的呈现HTML。 It accepts an optional parameter that is an object containing local variables for the view. 它接受一个可选参数,该参数是一个包含视图局部变量的对象。 It is like res.render(), except it cannot send the rendered view to the client on its own. 就像res.render()一样,区别在于它无法自行将渲染的视图发送给客户端。

To setup your view engine follow this, 要设置视图引擎,请按照以下步骤操作:

// set the view engine to ejs
app.set('view engine', 'ejs');

Assuming it's a static file, you can also just do; 假设它是一个静态文件,您也可以这样做;

app.use('/', express.static(__dirname + '/../public'));
//public being the folder containing your index.html.

//Example of Path;
//__dirname + '/../public'
__dirname = start in same folder as server.js.
/../ = go one folder back (in this case, to ROOT.
/public = enter the "public" folder, this is where our index.html is.

ROOT
  Server
    server.js
  Public
    css
    images
    index.html
    etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM