gpt4 book ai didi

javascript - Express 与浏览器结合使用 Node 同步

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:01 25 4
gpt4 key购买 nike

我对 JavaScript 世界非常陌生,我第一次尝试构建我的开发环境,我想要实现的目标应该很简单......

我想运行 Express 服务器以及浏览器同步来进行热重载,但我没有使用 gulp 或 grunt

但我不断收到此错误:

Starting the application in the development mode...
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
------------------------------------
Local: http://localhost:3000
External: http://10.111.234.196:3000
------------------------------------
[BS] Watching files...
events.js:160
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE :::3000

这就是我的脚本在 package.jason 文件中的样子

"scripts": {
"prestart": "babel-node buildScripts/startMessage.js",
"start": "npm-run-all --parallel security-check open:src",
"open:src": "babel-node buildScripts/srcServer.js & browser-sync start --proxy 'localhost:3000' --files 'src' --no-ui",
"security-check": "nsp check"
},

srcServer.js中:

import express from 'express';
import path from 'path';
import open from 'open';

const port = 3000;
const app = express();


app.get('/', function(request, response){
response.sendFile(path.join(__dirname, '../src/index.html'));
});

app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:'+ port)
}
});

并且在 bs-config.js 文件中是默认文件,我刚刚将 ui 更改为 false

This question给了我使用代理的提示,但我仍然收到该错误,我不知道为什么......请启发我,我想了解出了什么问题

最佳答案

我也遇到过类似的问题。看起来 BrowserSync 不再与 Express 在同一端口上工作。我设法使用 connect-browser-sync 中间件在不同的端口上运行它们。

这是我的server.js:

var express = require('express'),
bodyParser = require('body-parser'),
http = require('http'),
path = require('path'),
cors = require('cors');


// Express server
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);


// BrowserSync at development host
if (app.get('env') === 'development') {
var browserSync = require('browser-sync'),
var bsconf = {
host: 'localhost',
port: 3001,
https: false,
notify: false,
open: false,
online: false,
ui: false,
server: {
baseDir: path.join(__dirname, '/public')
},
files: [path.join(__dirname, '/public/**/*.{html,css,js,json}')]
};
var bs = browserSync.create().init(bsconf);

app.use(require('connect-browser-sync')(bs));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());


// Route index.html
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});


// Starting express server
http.createServer(app).listen(app.get('port'), function () {
console.log('Listening on port ' + app.get('port') + '...');
});

在端口 3000 上有一个 Express 服务器(没有页面自动重新加载)。在端口 3001 上有 BrowserSync 服务器,通过页面自动重新加载提供相同的内容。

关于javascript - Express 与浏览器结合使用 Node 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com