2017-08-07 201 views
0

我一直在試圖從角度服務傳遞多個參數給節點api。下面這裏是角服務代碼將參數傳遞給節點api

getEnrollmentId(userName,org) { 
console.log("username",userName); 
let headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' }); 
let options = new RequestOptions({ headers: headers }); 
let body1 = new URLSearchParams(); 
body1.set('username', userName); 
body1.set('orgName', org); 
let body = body1.toString(); 
console.log('server logs',body); 
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代碼是

app.post('/users', function(req, res) { 
var username = req.body.username; 
var orgName = req.body.orgName; 
    logger.debug('Body request',req); 
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 
     }); 
    } 
}); 

});

儘管我可以在body變量中看到我的參數值,但是當在我的節點控制檯上時,兩個參數均接收undefined值。 下面是節點控制檯日誌。 正如你可以看到我的請求對象,身體參數返回空數組body={}這可能是分配給undefined的原因參數值。任何解決方案來解決這個

[2017-08-07 22:17:06.186] [DEBUG] SampleWebApp - Body request IncomingMessage { 
    _readableState: 
    ReadableState { 
    objectMode: false, 
    highWaterMark: 16384, 
    buffer: BufferList { head: null, tail: null, length: 0 }, 
    length: 0, 
    pipes: null, 
    pipesCount: 0, 
    flowing: null, 
    ended: false, 
    endEmitted: false, 
    reading: false, 
    sync: true, 
    needReadable: false, 
    emittedReadable: false, 
    readableListening: false, 
    resumeScheduled: false, 
    defaultEncoding: 'utf8', 
    ranOut: false, 
    awaitDrain: 0, 
    readingMore: true, 
    decoder: null, 
    encoding: null }, 
    readable: true, 
    domain: null, 
    _events: {}, 
    _eventsCount: 0, 
    _maxListeners: undefined, 
    socket: 
    Socket { 
    connecting: false, 
    _hadError: false, 
    _handle: 
     TCP { 
     bytesRead: 830, 
     _externalStream: {}, 
     fd: 13, 
     reading: true, 
     owner: [Circular], 
     onread: [Function: onread], 
     onconnection: null, 
     writeQueueSize: 0, 
     _consumed: true }, 
    _parent: null, 
    _host: null, 
    _readableState: 
     ReadableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     buffer: [Object], 
     length: 0, 
     pipes: null, 
     pipesCount: 0, 
     flowing: true, 
     ended: false, 
     endEmitted: false, 
     reading: true, 
     sync: false, 
     needReadable: true, 
     emittedReadable: false, 
     readableListening: false, 
     resumeScheduled: false, 
     defaultEncoding: 'utf8', 
     ranOut: false, 
     awaitDrain: 0, 
     readingMore: false, 
     decoder: null, 
     encoding: null }, 
    readable: true, 
    domain: null, 
    _events: 
     { end: [Object], 
     finish: [Function: onSocketFinish], 
     _socketEnd: [Function: onSocketEnd], 
     drain: [Object], 
     timeout: [Function], 
     error: [Function: socketOnError], 
     close: [Object], 
     data: [Function: socketOnData], 
     resume: [Function: onSocketResume], 
     pause: [Function: onSocketPause] }, 
    _eventsCount: 10, 
    _maxListeners: undefined, 
    _writableState: 
     WritableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     needDrain: false, 
     ending: false, 
     ended: false, 
     finished: false, 
     decodeStrings: false, 
     defaultEncoding: 'utf8', 
     length: 0, 
     writing: false, 
     corked: 0, 
     sync: false, 
     bufferProcessing: false, 
     onwrite: [Function], 
     writecb: null, 
     writelen: 0, 
     bufferedRequest: null, 
     lastBufferedRequest: null, 
     pendingcb: 0, 
     prefinished: false, 
     errorEmitted: false, 
     bufferedRequestCount: 0, 
     corkedRequestsFree: [Object] }, 
    writable: true, 
    allowHalfOpen: true, 
    destroyed: false, 
    _bytesDispatched: 287, 
    _sockname: null, 
    _pendingData: null, 
    _pendingEncoding: '', 
    server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _idleTimeout: 240000, 
    _idleNext: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idlePrev: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idleStart: 46633, 
    parser: 
     HTTPParser { 
     '0': [Function: parserOnHeaders], 
     '1': [Function: parserOnHeadersComplete], 
     '2': [Function: parserOnBody], 
     '3': [Function: parserOnMessageComplete], 
     '4': [Function: onParserExecute], 
     _headers: [], 
     _url: '', 
     _consumed: true, 
     socket: [Circular], 
     incoming: [Circular], 
     outgoing: null, 
     maxHeaderPairs: 2000, 
     onIncoming: [Function: parserOnIncoming] }, 
    on: [Function: socketOnWrap], 
    _paused: false, 
    read: [Function], 
    _consuming: true, 
    _httpMessage: 
     ServerResponse { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 1, 
     _maxListeners: undefined, 
     output: [], 
     outputEncodings: [], 
     outputCallbacks: [], 
     outputSize: 0, 
     writable: true, 
     _last: false, 
     upgrading: false, 
     chunkedEncoding: false, 
     shouldKeepAlive: true, 
     useChunkedEncodingByDefault: true, 
     sendDate: true, 
     _removedHeader: {}, 
     _contentLength: null, 
     _hasBody: true, 
     _trailer: '', 
     finished: false, 
     _headerSent: false, 
     socket: [Circular], 
     connection: [Circular], 
     _header: null, 
     _headers: [Object], 
     _headerNames: [Object], 
     _onPendingData: [Function: updateOutgoingData], 
     req: [Circular], 
     locals: {} } }, 
    connection: 
    Socket { 
    connecting: false, 
    _hadError: false, 
    _handle: 
     TCP { 
     bytesRead: 830, 
     _externalStream: {}, 
     fd: 13, 
     reading: true, 
     owner: [Circular], 
     onread: [Function: onread], 
     onconnection: null, 
     writeQueueSize: 0, 
     _consumed: true }, 
    _parent: null, 
    _host: null, 
    _readableState: 
     ReadableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     buffer: [Object], 
     length: 0, 
     pipes: null, 
     pipesCount: 0, 
     flowing: true, 
     ended: false, 
     endEmitted: false, 
     reading: true, 
     sync: false, 
     needReadable: true, 
     emittedReadable: false, 
     readableListening: false, 
     resumeScheduled: false, 
     defaultEncoding: 'utf8', 
     ranOut: false, 
     awaitDrain: 0, 
     readingMore: false, 
     decoder: null, 
     encoding: null }, 
    readable: true, 
    domain: null, 
    _events: 
     { end: [Object], 
     finish: [Function: onSocketFinish], 
     _socketEnd: [Function: onSocketEnd], 
     drain: [Object], 
     timeout: [Function], 
     error: [Function: socketOnError], 
     close: [Object], 
     data: [Function: socketOnData], 
     resume: [Function: onSocketResume], 
     pause: [Function: onSocketPause] }, 
    _eventsCount: 10, 
    _maxListeners: undefined, 
    _writableState: 
     WritableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     needDrain: false, 
     ending: false, 
     ended: false, 
     finished: false, 
     decodeStrings: false, 
     defaultEncoding: 'utf8', 
     length: 0, 
     writing: false, 
     corked: 0, 
     sync: false, 
     bufferProcessing: false, 
     onwrite: [Function], 
     writecb: null, 
     writelen: 0, 
     bufferedRequest: null, 
     lastBufferedRequest: null, 
     pendingcb: 0, 
     prefinished: false, 
     errorEmitted: false, 
     bufferedRequestCount: 0, 
     corkedRequestsFree: [Object] }, 
    writable: true, 
    allowHalfOpen: true, 
    destroyed: false, 
    _bytesDispatched: 287, 
    _sockname: null, 
    _pendingData: null, 
    _pendingEncoding: '', 
    server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _idleTimeout: 240000, 
    _idleNext: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idlePrev: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idleStart: 46633, 
    parser: 
     HTTPParser { 
     '0': [Function: parserOnHeaders], 
     '1': [Function: parserOnHeadersComplete], 
     '2': [Function: parserOnBody], 
     '3': [Function: parserOnMessageComplete], 
     '4': [Function: onParserExecute], 
     _headers: [], 
     _url: '', 
     _consumed: true, 
     socket: [Circular], 
     incoming: [Circular], 
     outgoing: null, 
     maxHeaderPairs: 2000, 
     onIncoming: [Function: parserOnIncoming] }, 
    on: [Function: socketOnWrap], 
    _paused: false, 
    read: [Function], 
    _consuming: true, 
    _httpMessage: 
     ServerResponse { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 1, 
     _maxListeners: undefined, 
     output: [], 
     outputEncodings: [], 
     outputCallbacks: [], 
     outputSize: 0, 
     writable: true, 
     _last: false, 
     upgrading: false, 
     chunkedEncoding: false, 
     shouldKeepAlive: true, 
     useChunkedEncodingByDefault: true, 
     sendDate: true, 
     _removedHeader: {}, 
     _contentLength: null, 
     _hasBody: true, 
     _trailer: '', 
     finished: false, 
     _headerSent: false, 
     socket: [Circular], 
     connection: [Circular], 
     _header: null, 
     _headers: [Object], 
     _headerNames: [Object], 
     _onPendingData: [Function: updateOutgoingData], 
     req: [Circular], 
     locals: {} } }, 
    httpVersionMajor: 1, 
    httpVersionMinor: 1, 
    httpVersion: '1.1', 
    complete: false, 
    headers: 
    { host: 'localhost:4000', 
    'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0', 
    accept: 'application/json, text/plain, */*', 
    'accept-language': 'en-US,en;q=0.5', 
    'accept-encoding': 'gzip, deflate', 
    'content-type': 'x-www-form-urlencoded', 
    referer: 'http://localhost:4200/', 
    'content-length': '26', 
    origin: 'http://localhost:4200', 
    connection: 'keep-alive' }, 
    rawHeaders: 
    [ 'Host', 
    'localhost:4000', 
    'User-Agent', 
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0', 
    'Accept', 
    'application/json, text/plain, */*', 
    'Accept-Language', 
    'en-US,en;q=0.5', 
    'Accept-Encoding', 
    'gzip, deflate', 
    'Content-Type', 
    'x-www-form-urlencoded', 
    'Referer', 
    'http://localhost:4200/', 
    'Content-Length', 
    '26', 
    'Origin', 
    'http://localhost:4200', 
    'Connection', 
    'keep-alive' ], 
    trailers: {}, 
    rawTrailers: [], 
    upgrade: false, 
    url: '/users', 
    method: 'POST', 
    statusCode: null, 
    statusMessage: null, 
    client: 
    Socket { 
    connecting: false, 
    _hadError: false, 
    _handle: 
     TCP { 
     bytesRead: 830, 
     _externalStream: {}, 
     fd: 13, 
     reading: true, 
     owner: [Circular], 
     onread: [Function: onread], 
     onconnection: null, 
     writeQueueSize: 0, 
     _consumed: true }, 
    _parent: null, 
    _host: null, 
    _readableState: 
     ReadableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     buffer: [Object], 
     length: 0, 
     pipes: null, 
     pipesCount: 0, 
     flowing: true, 
     ended: false, 
     endEmitted: false, 
     reading: true, 
     sync: false, 
     needReadable: true, 
     emittedReadable: false, 
     readableListening: false, 
     resumeScheduled: false, 
     defaultEncoding: 'utf8', 
     ranOut: false, 
     awaitDrain: 0, 
     readingMore: false, 
     decoder: null, 
     encoding: null }, 
    readable: true, 
    domain: null, 
    _events: 
     { end: [Object], 
     finish: [Function: onSocketFinish], 
     _socketEnd: [Function: onSocketEnd], 
     drain: [Object], 
     timeout: [Function], 
     error: [Function: socketOnError], 
     close: [Object], 
     data: [Function: socketOnData], 
     resume: [Function: onSocketResume], 
     pause: [Function: onSocketPause] }, 
    _eventsCount: 10, 
    _maxListeners: undefined, 
    _writableState: 
     WritableState { 
     objectMode: false, 
     highWaterMark: 16384, 
     needDrain: false, 
     ending: false, 
     ended: false, 
     finished: false, 
     decodeStrings: false, 
     defaultEncoding: 'utf8', 
     length: 0, 
     writing: false, 
     corked: 0, 
     sync: false, 
     bufferProcessing: false, 
     onwrite: [Function], 
     writecb: null, 
     writelen: 0, 
     bufferedRequest: null, 
     lastBufferedRequest: null, 
     pendingcb: 0, 
     prefinished: false, 
     errorEmitted: false, 
     bufferedRequestCount: 0, 
     corkedRequestsFree: [Object] }, 
    writable: true, 
    allowHalfOpen: true, 
    destroyed: false, 
    _bytesDispatched: 287, 
    _sockname: null, 
    _pendingData: null, 
    _pendingEncoding: '', 
    server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _server: 
     Server { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 2, 
     _maxListeners: undefined, 
     _connections: 1, 
     _handle: [Object], 
     _usingSlaves: false, 
     _slaves: [], 
     _unref: false, 
     allowHalfOpen: true, 
     pauseOnConnect: false, 
     httpAllowHalfOpen: false, 
     timeout: 240000, 
     _pendingResponseData: 0, 
     _connectionKey: '6::::4000' }, 
    _idleTimeout: 240000, 
    _idleNext: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idlePrev: 
     TimersList { 
     _idleNext: [Circular], 
     _idlePrev: [Circular], 
     _timer: [Object], 
     _unrefed: true, 
     msecs: 240000, 
     nextTick: false }, 
    _idleStart: 46633, 
    parser: 
     HTTPParser { 
     '0': [Function: parserOnHeaders], 
     '1': [Function: parserOnHeadersComplete], 
     '2': [Function: parserOnBody], 
     '3': [Function: parserOnMessageComplete], 
     '4': [Function: onParserExecute], 
     _headers: [], 
     _url: '', 
     _consumed: true, 
     socket: [Circular], 
     incoming: [Circular], 
     outgoing: null, 
     maxHeaderPairs: 2000, 
     onIncoming: [Function: parserOnIncoming] }, 
    on: [Function: socketOnWrap], 
    _paused: false, 
    read: [Function], 
    _consuming: true, 
    _httpMessage: 
     ServerResponse { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 1, 
     _maxListeners: undefined, 
     output: [], 
     outputEncodings: [], 
     outputCallbacks: [], 
     outputSize: 0, 
     writable: true, 
     _last: false, 
     upgrading: false, 
     chunkedEncoding: false, 
     shouldKeepAlive: true, 
     useChunkedEncodingByDefault: true, 
     sendDate: true, 
     _removedHeader: {}, 
     _contentLength: null, 
     _hasBody: true, 
     _trailer: '', 
     finished: false, 
     _headerSent: false, 
     socket: [Circular], 
     connection: [Circular], 
     _header: null, 
     _headers: [Object], 
     _headerNames: [Object], 
     _onPendingData: [Function: updateOutgoingData], 
     req: [Circular], 
     locals: {} } }, 
    _consuming: false, 
    _dumped: false, 
    next: [Function: next], 
    baseUrl: '', 
    originalUrl: '/users', 
    _parsedUrl: 
    Url { 
    protocol: null, 
    slashes: null, 
    auth: null, 
    host: null, 
    port: null, 
    hostname: null, 
    hash: null, 
    search: null, 
    query: null, 
    pathname: '/users', 
    path: '/users', 
    href: '/users', 
    _raw: '/users' }, 
    params: {}, 
    query: {}, 
    res: 
    ServerResponse { 
    domain: null, 
    _events: { finish: [Function: resOnFinish] }, 
    _eventsCount: 1, 
    _maxListeners: undefined, 
    output: [], 
    outputEncodings: [], 
    outputCallbacks: [], 
    outputSize: 0, 
    writable: true, 
    _last: false, 
    upgrading: false, 
    chunkedEncoding: false, 
    shouldKeepAlive: true, 
    useChunkedEncodingByDefault: true, 
    sendDate: true, 
    _removedHeader: {}, 
    _contentLength: null, 
    _hasBody: true, 
    _trailer: '', 
    finished: false, 
    _headerSent: false, 
    socket: 
     Socket { 
     connecting: false, 
     _hadError: false, 
     _handle: [Object], 
     _parent: null, 
     _host: null, 
     _readableState: [Object], 
     readable: true, 
     domain: null, 
     _events: [Object], 
     _eventsCount: 10, 
     _maxListeners: undefined, 
     _writableState: [Object], 
     writable: true, 
     allowHalfOpen: true, 
     destroyed: false, 
     _bytesDispatched: 287, 
     _sockname: null, 
     _pendingData: null, 
     _pendingEncoding: '', 
     server: [Object], 
     _server: [Object], 
     _idleTimeout: 240000, 
     _idleNext: [Object], 
     _idlePrev: [Object], 
     _idleStart: 46633, 
     parser: [Object], 
     on: [Function: socketOnWrap], 
     _paused: false, 
     read: [Function], 
     _consuming: true, 
     _httpMessage: [Circular] }, 
    connection: 
     Socket { 
     connecting: false, 
     _hadError: false, 
     _handle: [Object], 
     _parent: null, 
     _host: null, 
     _readableState: [Object], 
     readable: true, 
     domain: null, 
     _events: [Object], 
     _eventsCount: 10, 
     _maxListeners: undefined, 
     _writableState: [Object], 
     writable: true, 
     allowHalfOpen: true, 
     destroyed: false, 
     _bytesDispatched: 287, 
     _sockname: null, 
     _pendingData: null, 
     _pendingEncoding: '', 
     server: [Object], 
     _server: [Object], 
     _idleTimeout: 240000, 
     _idleNext: [Object], 
     _idlePrev: [Object], 
     _idleStart: 46633, 
     parser: [Object], 
     on: [Function: socketOnWrap], 
     _paused: false, 
     read: [Function], 
     _consuming: true, 
     _httpMessage: [Circular] }, 
    _header: null, 
    _headers: 
     { 'x-powered-by': 'Express', 
     'access-control-allow-origin': '*' }, 
    _headerNames: 
     { 'x-powered-by': 'X-Powered-By', 
     'access-control-allow-origin': 'Access-Control-Allow-Origin' }, 
    _onPendingData: [Function: updateOutgoingData], 
    req: [Circular], 
    locals: {} }, 
    body: {}, 
    token: undefined, 
    route: Route { path: '/users', stack: [ [Object] ], methods: { post: true } } } 
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - End point : /users 
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - User name : undefined 
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - Org name : undefined 
+0

不要在body1對象上執行'toString()'。傳遞一個常規的JSON對象是最容易的,所以'let body = {username:'myname',orgName:'MyOrg'}' – Ero

回答

0

您正在發送具有 'Content-Type的' 數據: '×WWW的形式進行了urlencoded' 報頭;如果要解析身體,我建議安裝body-parse模塊(請參閱提議的解決方案here)。

或者,如果你能要求的Content-Type改變

'Content-type': 'application/json' 

你的代碼在服務器端應該工作,因爲它是。

+0

我已經安裝了'body-parser'並在我的節點服務器文件中調用它。其次,當我嘗試將內容類型更改爲「application/json」時,我收到錯誤「意外的令牌」。當我通過firefox中的網絡標籤進行調試時,我得到'400錯誤請求'狀態。傳入json請求的主體是'username = bill&org = org1'。是否應該像這個'{username:bill&org:org1}'? –