Sayak Mukhopadhyay
Sayak Mukhopadhyay

Reputation: 1464

Passing special characters like '+' (plus) from Angular to Express.js not working

I have a web app with angular front end running on Angular 4.3.6 with express.js handling routing at the back end. I am trying to query from angular using

getStuff(name: string): Observable<string> {
    return this.http.get<string>('/someroute', {
        params: new HttpParams().set('name', name)
    });
}

Now this name variable can contain something like ABC+XYZ, a string actually present in the server. This code actually sends this to the backend /someroute?name=ABC+XYZ

My express code is set up like

router.get('/someroute', (req, res, next) => {
    console.log(req.query.name)
}

console.log() outputs ABC XYZ. Express is converting the + as a space.

I tried Url Encoding the name parameter in angular like

params: new HttpParams().set('name', encodeURIComponent(name))

But this causes Angular to convert %2B(code for +) to %252B(%25 is code for %).

Also, according to my title, I will need a solution for other special characters too. I know how to do this in a hacky way but I am looking for a non hacky solution to this.

Upvotes: 0

Views: 1395

Answers (1)

sterms
sterms

Reputation: 81

I've encountered a similar situation and after much frustration I've realized that using string interpolation and replace works.

const params = new HttpParams().set('name', name);

getStuff(name: string): Observable<string> {
    return this.http.get<string>(`/someroute/?${params.toString().replace(/\+/g, '%2B')}`);
}

If you were attempting to do this with characters used in Query Parameters (like '=' or '&') you could probably build the url and it's parameters manually instead of using HttpParams:

getStuff(name: string): Observable<string> {
    return this.http.get<string>(`/someroute/?someValue=${myValue.replace(/\+/g, '%2B')}&anotherValue=${anotherVal}`);
}

Upvotes: 1

Related Questions