Home > Mobile >  Multi-Line Strings As Parameters
Multi-Line Strings As Parameters

Time:01-04

How can you pass multi-line strings (with spaces and tabs) as a parameter to an express server?

Express.js code that accepts the parameter :

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

Client-Side Javascript code that tries to send a multi-line string :

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()
        });
}

When I send a multi-line string as the parameter, the variable "prompt" is equal to "undefined". How do I solve this?

Update: Added the code that sends a request with the string for more clarity

CodePudding user response:

An URL cannot contain newlines. A HTTP resource name must be a single-line string and should not contain spaces either.

To work around this limitation, you need to URL encode the prompt parameter via encodeURIComponent:

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

To get this value in Express.js, you can use a route parameter and access it via req.params which will automatically decode it. Notice that you need to use (*) to allow slashes in the parameter:

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

Alternatively, you can (and probably should) send the value using an URL query string parameter:

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

In Express.js, you use req.query (as you did) to access it:

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