Escape symbols in NodeJS

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
    
asked by anonymous 02.03.2018 / 16:18

1 answer

2

Basically you simply replace the character of + with %2B and the character & with %26 .

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

npm install urlencode

To use it, you should import:

const urlencode = require('urlencode');

And change the parameter body of method fetch :

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

If you need to decode:

const msg = urlencode.decode(req.body.phrase);
    
03.03.2018 / 00:32