0
我使用node.js作爲restAPI &使應用程序,但在本地主機測試我想使用另一臺共享的PC,所以我添加一些代碼建議here並且還添加類似的代碼Node.js偵聽EADDRNOTAVAIL使用ipaddress共享pc呼叫
app.listen(3000, '192.168.100.102', function() { console.log('Listening to port: ' + 3000); });
我使用默認使用js的表達結構中定義here
如果你想展示我的代碼,那麼它就像
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var funclib = require('./routes/functions/functionLib');
var moduleNm = 'app.js';
var dbfunction = require('./routes/functions/dbfunction');
var connectDB = dbfunction.connectDB(moduleNm);
var nodeSmtp = require('./routes/functions/nodemailer_smtp');
var mysql = require('mysql');
var connection = require("express-myconnection");
var app = express();
app.set('host', '192.168.100.102');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000, '192.168.100.102', function() {
console.log('Listening to port: ' + 3000);
});
module.exports = app;
我希望細節就夠了。 由於事先
你的意思是說'app.set('host','0.0.0.0');'這個?或者像'app.listen(3000,'0.0.0.0',function(){ console.log('Listening to port:'+ 3000); });' –
因爲你目前沒有使用'app。 get('host')'任何地方,你只需要改變'app.listen()'。如果你想聽所有的接口,你也可以忽略IP地址:'app.listen(3000,function(){...})' – mscdex