Escape symbols in Nodejs

Asked

Viewed 76 times

0

I have the following code running on Nodejs

/*jshint esversion: 6 */
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.use(bodyParser.urlencoded({extended: false}));
app.post("/home", (req, res)=>{
    res.set("Content-Type", "text/plain");
    res.set("Accept-Charset", "utf-8");
    const msg = req.body.phrase;
    console.log("RECEIVED: "+msg);
    res.send("frase : "+msg);
});
app.listen(port, (err)=>{
    if (err){
        throw err;
    }
    console.log("Server started on http://localhost:"+port);
});

when I make a request via post containing the characters + and &, these characters are replaced or the result returns wrong, example of the request:

fetch("http://localhost:8080/home", {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, 
    body: 'phrase=eu+ela&voce'
}).then(function(response){
    return response.text();
  }).then(function(text){
  	console.log(text); 
  });

eu+voce&ela

returns

 eu voce

1 answer

2


Basically just replace the character of + for %2B and the character & for %26.

But you can use the library urlencode to help in this process, to install just run the command:

npm install urlencode

To use it, you must import:

const urlencode = require('urlencode');

And change the parameter body of the method fetch:

body: `phrase=${urlencode('eu+ela&voce')}`

If there is a need to decode:

const msg = urlencode.decode(req.body.phrase);
  • thank you very much my friend!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.