mohammad obaid
mohammad obaid

Reputation: 413

Passing parameters in angular4 services

I have been trying to pass two parameter from my angular frontend to node api. However I am getting error on my node console that paramter value is missing or invalid when I run my app. Below here is node api code

app.post('/users', function(req, res) {
var username = req.body.username;
var orgName = req.body.orgName;
logger.debug('End point : /users');
logger.debug('User name : ' + username);
logger.debug('Org name  : ' + orgName);
if (!username) {
    res.json(getErrorMessage('\'username\''));
    return;
}
if (!orgName) {
    res.json(getErrorMessage('\'orgName\''));
    return;
}
var token = jwt.sign({
    exp: Math.floor(Date.now() / 1000) + parseInt(config.jwt_expiretime),
    username: username,
    orgName: orgName
}, app.get('secret'));
helper.getRegisteredUsers(username, orgName, true).then(function(response) {
    if (response && typeof response !== 'string') {
        response.token = token;
        res.json(response);
    } else {
        res.json({
            success: false,
            message: response
        });
    }
});

});

Here is my angular service code . For the sake of demonstration , I am passing dummy values from angular service

getEnrollmentId(userName,org) {
let headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = "'username=Barry&orgName=org2'";
return this.http.post('http://localhost:4000/users', body, options )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error shit'));

}

When I try to acheive same thing using curl query by calling node api and passing paramters , I am successfully able to post data and return response from api. Below here is curl query

 curl -s -X POST \
 http://localhost:4000/users \
 -H "content-type: application/x-www-form-urlencoded" \
 -d 'username=Jim&orgName=org1'

What am I doing wrong in my angular services?

Upvotes: 0

Views: 531

Answers (1)

pritesh agrawal
pritesh agrawal

Reputation: 1225

Pass the parameter as url search params , below code should help

let body = new URLSearchParams();
body.set('username', username);
body.set('orgName', orgName);

Upvotes: 1

Related Questions