Node.js服务器只是不断加载而没有结果

时间:2018-07-25 12:59:07

标签: node.js

server.js

const http = require('http');
const app  = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);

app.js

const express = require('express');
const app = express();
const productRoutes = require('./api/routes/products');
app.use('/products', productRoutes);
module.exports = app;

因此,当我只运行代码节点server.js时,它只会不断循环而没有任何结果。

4 个答案:

答案 0 :(得分:1)

查看此link,它会提供更多有关其工作原理的详细信息。

const http = require('http');
const net = require('net');
const url = require('url');

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
  // connect to an origin server
  const srvUrl = url.parse(`http://${req.url}`);
  const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
    cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                    'Proxy-agent: Node.js-Proxy\r\n' +
                    '\r\n');
    srvSocket.write(head);
    srvSocket.pipe(cltSocket);
    cltSocket.pipe(srvSocket);
  });
});

// now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {

  // make a request to a tunneling proxy
  const options = {
    port: 1337,
    hostname: '127.0.0.1',
    method: 'CONNECT',
    path: 'www.google.com:80'
  };

  const req = http.request(options);
  req.end();

  req.on('connect', (res, socket, head) => {
    console.log('got connected!');

    // make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', (chunk) => {
      console.log(chunk.toString());
    });
    socket.on('end', () => {
      proxy.close();
    });
  });
});

答案 1 :(得分:0)

const http = require('http');
const app  = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);

据我所知,您的server.js中最有可能发生的事情是您的服务器正在等待某些请求。而且您的代码中没有任何内容可以处理请求。

答案 2 :(得分:0)

我认为您必须调用require函数以返回实际的router对象,尝试更改此行

来自:const productRoutes = require('./api/routes/products');

收件人:const productRoutes = require('./api/routes/products')();

答案 3 :(得分:0)

您必须在http.createServer中指定应用程序

server.js

const http = require('http');
const app  = require('./app');
const port = process.env.PORT || 3000;
//here
const server = http.createServer(app);
server.listen(port);