这是路线功能:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Abcd1234',
database: 'mtest'
});
connection.connect()
global.products = "abc"
connection.query('SELECT name from catalog_product_flat_1', function (err, rows, fields) {
if (err) throw err
global.products = rows[0].name;
})
connection.end()
console.log('Product is: ', products)
res.render(
'product', { products: global.products, title: 'abc' }
);
});
module.exports = router;
无论我如何不能将查询结果分配给产品,产品:global.products最终都是未定义的,任何人都知道该怎么做?
答案 0 :(得分:0)
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebServletConfiguration implements WebApplicationInitializer{
public void onStartup(ServletContext ctx) throws ServletException {
AnnotationConfigWebApplicationContext webCtx = new AnnotationConfigWebApplicationContext();
webCtx.register(SpringConfig.class);
webCtx.setServletContext(ctx);
ServletRegistration.Dynamic servlet = ctx.addServlet("dispatcher", new DispatcherServlet(webCtx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
是一种异步方法,将渲染逻辑移入函数中。试试这个,
connection.query
还有下面提到的@Raghav Garg,在每个请求上连接数据库都不是理想的选择(或者,如果该请求未得到太多调用,则可能是理想的选择,因此您不希望通过数据库,取决于您的要求)。但是我相信这是另一个与您的问题无关的性能优化。
答案 1 :(得分:0)
欢迎来到异步编程。您的代码可以这样写:
var express = require('express');
var mysql = require('mysql')
var router = express.Router();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Abcd1234',
database: 'mtest'
}).connect();
/* GET users listing. */
router.get('/', function (req, res, next) {
connection.query('SELECT name from catalog_product_flat_1', function (err, rows, fields) {
if (err) throw err
res.render('product', { products: rows, title: 'abc' });
});
});
process.on('SIGTERM', () => {
console.info('SIGTERM signal received.');
connection.end()
});
module.exports = router;
在上面的代码中,
请阅读有关js异步性质及其处理方式的更多信息。您当前正在使用callbacks
,但是现在我们有更多的方式,例如promises
和async/await
。 https://medium.com/@tkssharma/writing-neat-asynchronous-node-js-code-with-promises-async-await-fa8d8b0bcd7c