两个问题,1.在快速路由器上2.请求,响应

时间:2018-07-21 01:23:50

标签: node.js reactjs express nginx

[环境] node.js, 表达, 反应, nginx

[第一个问题] 如果我已经重新加载了除根URL以外的网站,则会收到错误消息“无法获取/...”

[第二个问题] 当我通过ajax向服务器端请求超过6次时,网站已停止并且没有响应。如果我重新启动服务器,则可以再次从服务器获得5次响应... 这个错误对我来说至关重要。

我的密码..! [客户]

	
  // request to server
  fetchInfo = async () => {
		const { id } = this.props.params;
		const room = await webster.get("/api/v1/conference/"+id);

		this.setState({
			info: room
		});
	}
  
  //webster.get - ajax
  function get(url, data) {
	const get =	$.ajax({
		url,
		data,
		type: "get",
		dataType: "json",
	});
	const error = get.fail(() => {
		throw new Error("Error occured in request");
	});
	const info = get.done(info => {
		return info;
	});
	return info || error;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

[后端]

//app.js

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Attach database pool for req object
app.use((req, res, next) => {
	req.db = pool;
	allowCrossDomain;
	next();
});

var allowCrossDomain = function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
	res.header('Access-Control-Allow-Headers', 'Content-Type'); next();
} ;

//set route for prod
app.get('/', (req, res) => {
	res.sendFile(path.join(__dirname + '/../public/dist'+ 'index.html'));
});

app.use('/', express.static(path.join(__dirname + '/../public')));
app.use('/api/v1/user', user);
app.use('/api/v1/conference', conference);

module.exports = {
	app
};



//api/conference/index.js
const router = require('express').Router();
const _get = require('./get');

router.get('/', (req, res) => {
	_get.searchConferenceRoom(req, res);
});

router.get('/:id', (req, res) => {
	_get.getRoomInfo(req, res); //request query to db
});

module.exports = router;



//www.js - exec file
const { app } = require('../app');
const port = require('../settings.json').http.port;
const httpServer = require('http').Server(app);

app.set('port', process.env.PORT || port);

//set port
httpServer.listen(app.get('port'), () => {
	console.log('Express started on http://localhost:' + app.get('port'));
});

1 个答案:

答案 0 :(得分:0)

关于第一个问题

  

如果我重新加载了根URL以外的网站,则会收到错误消息“无法获取/...”

这是可以预期的,因为当您浏览路由器链接时,Javascript将运行并处理地址栏中的URL,而不会导致页面刷新,从而进行页面转换

解决方案是做一条“包罗万象”的路线

只需在将所有请求发送到索引index.html的服务器上设置一个包罗万象的内容

类似的东西

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

,但请确保在您的剩余api之后执行此路线

关于第二个问题还不清楚,如果我想猜测一下,我认为请求的处理程序陷入困境,直到您将其终止才响应客户端