gpt4 book ai didi

javascript - 如何在nodejs中提供文件之前保存变量

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

给出以下代码:

 const https = require('https');
const fs = require('fs');
var path = require('path');
const express = require('express');
const app = express();
const router = express.Router();
const pool = require('./mysqldb.js');
const pathView = __dirname + "/views/";
const IMGPath = "/public";
var bodyParser = require("body-parser");
const listenPort = 8010;
var id = null ;

router.get('/details/:id', async function (req, res, next) {
id = req.params.id;
if ( typeof req.params.id === "number"){id = parseInt(id);}
res.render('details.ejs' );
});

主要目标是在提供details.ejs文件之前将req.params.id(来自url的id)保存在id变量中。我尝试删除异步但没有成功。你能帮我吗?

最佳答案

您可以在 async 函数中使用 await 关键字,如下所示:

router.get('/details/:id', async function (req, res, next) {
await (() => { id = req.params.id; })(); // Will run first
await (() => { res.send(id); })(); // Will run second
})

res.send(id)res.render('details.ejs') (在您的情况下)将在检索 id 后运行

关于javascript - 如何在nodejs中提供文件之前保存变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937402/

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