繁体   English   中英

多行字符串作为参数

[英]Multi-Line Strings As Parameters

如何将多行字符串(带有空格和制表符)作为参数传递给快速服务器?

接受参数的Express.js代码:

app.get('/:prompt', async (req, res) => {
  const prompt = req.query.prompt;
  // Do something with the prompt and send a response
}

尝试发送多行字符串的客户端 Javascript 代码:

export function btn_click() {
    console.log('Clicked')
    const prompt = $w("#textBox1").value
    // console.log(typeof prompt);
    const Orignal_URL = 'https://11bf-2401-4900-1f35-97fc-68a4-6e62-bb93-34d5.in.ngrok.io/';
    const URL = Orignal_URL.concat(prompt)
    console.log(URL);

    fetch(URL, { method: 'get' })
        .then(res => res.json())
        .then(ans => {
            console.log(ans);
            const blank = $w("#text3");
            if (ans['Answer'] === undefined){
                blank.text = 'Please enter the required information';
            }
            else {
                blank.text = String(ans['Answer']);
            }
            blank.show()
        });
}

当我发送多行字符串作为参数时,变量“prompt”等于“undefined”。 我该如何解决这个问题?

更新:添加了发送带有字符串的请求的代码,以便更清楚

URL 不能包含换行符。 HTTP 资源名称必须是单行字符串,并且不应包含空格

要解决此限制,您需要通过encodeURIComponent URL 对提示参数进行编码:

const url = `https://example.org/app/${ encodeURIComponent(prompt) }`;

要在 Express.js 中获取此值,您可以使用路由参数并通过req.params访问它,这将自动对其进行解码。 请注意,您需要使用(*)允许在参数中使用斜线

app.get('/app/:prompt(*)', async (req, res) => {
  const prompt = req.params.prompt;
  // Do something with the prompt and send a response
});

或者,您可以(并且可能应该)使用URL 查询字符串参数发送值:

const url = `https://example.org/app?prompt=${ encodeURIComponent(prompt) }`;

在 Express.js 中,您使用req.query (就像您所做的那样)来访问它:

app.get('/app', async (req, res) => {
  const prompt = req.query.prompt;
  // Do something with the prompt and send a response
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM