2017-08-06 68 views
0

嘿,我一直在試圖從我的角度前端傳遞兩個參數到節點api。不過,當我運行我的應用時,我的節點控制檯上出現錯誤paramter value is missing or invalid。 下面是節點api代碼在angular4服務中傳遞參數

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

});

這是我的角度服務代碼。爲了演示起見,我從角服務

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')); 

}傳遞出的僞值

當我嘗試通過調用節點API和傳遞paramters使用curl查詢acheive同樣的事情,我能夠成功發佈數據並從api返回響應。下面這裏是捲曲查詢

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

我在我的角度服務做錯了什麼?

回答

1

傳遞參數的URL搜索參數,可以 下面的代碼應該幫助

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

它沒有工作。在我的節點api中,它正在接收這些參數的未定義值。以下是節點控制檯的屏幕截圖https://user-images.githubusercontent.com/26554206/29001906-f9664aac-7aae-11e7-9879-35f6128a2710.png –

+0

如何定義變量(username和orgName),它包含值。 –

+0

這裏是要點鏈接https://gist.github.com/mohammadobaid1/fd809e4cf8ece1078a6f2d57cbfb5b19其中包含我的組件代碼,它調用我的角度服務和角度前端HTML代碼,從前端檢索值。 –