简体   繁体   English

Node.js server.get()TypeError:未定义不是函数

[英]Node.js server.get() TypeError: undefined is not a function

var express = require('express'),
    http = require('http'),
    app = express(),
    server = http.createServer(app),
    io = require('socket.io').listen(server), //pass a http.Server instance
    fs = require('fs');

server.listen(8008);

// routing
server.get('/', function (req, res) {
  res.sendfile(__dirname + '/chat.html');
});

I have this code which creates a server. 我有创建服务器的这段代码。 When I run this I get the following error: TypeError: undefined is not a function 运行此命令时,出现以下错误:TypeError:undefined不是函数

server.get('/', function (req, res) {
       ^
TypeError: undefined is not a function
    at Object.<anonymous> (C:\Users\rexhi\Desktop\private_mess\app.js:11:8)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

What is wrong here? 怎么了 I'm new to Node. 我是Node的新手。

The .get(req,res) function belongs to an instance of express . .get(req,res)函数属于express的实例。 Thus, you should do: 因此,您应该执行以下操作:

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

It looks to me like you are trying to use express to handle your routing, if that is the case then you want to use app.get() not server.get() . 在我看来,您正在尝试使用Express处理路由,如果是这种情况,则您要使用app.get()而不是server.get() So in your case something like 所以在你的情况下

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/chat.html');
});

Take a look at the express routing reference for more info - http://expressjs.com/guide/routing.html 看看快速路由参考以了解更多信息-http: //expressjs.com/guide/routing.html

Use app.get() instead of server.get() 使用app.get()代替server.get()

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/chat.html');
});

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

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