#node.js #express
Вопрос:
Я только что создал проект в NodeJS и пытаюсь выполнить запрос на публикацию с моего интерфейса (через API). Все работает нормально, запрос post успешно выполнен, все параметры отправлены, и мое приложение NodeJS получает запрос, однако тело/параметры пусты.
Вот код, который я использую:
const http = require('http'); const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const hostname = '127.0.0.1'; const port = 3000; const app = express(); const corsOptions = { origin: 'http://localhost:4200', allowedHeaders: ['Content-Type'] } app.options('*', cors(corsOptions)); app.use(cors(corsOptions)); app.use(bodyParser.urlencoded({extended : true})); app.use(bodyParser.json()); app.post('/', function (req, res) { console.log(req); res.send('Hello World!'); })
Приложение показывает «Привет, мир», когда я отправляю сообщение по пути по умолчанию, а также показывает всю req
информацию, но параметры пусты {}
Вот мой код на стороне клиента:
testPost(parameter1: any, parameter2: any): Observablelt;anygt; { return this.http.post(URL_API.url, {'parameter1': parameter1, 'parameter2': parameter2}, {headers: new HttpHeaders({'Content-Type': '*'})}); }
Вот что я получаю в NodeJS:
lt;ref *2gt; IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: null, ended: false, endEmitted: false, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: true, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: true, decoder: null, encoding: null, [Symbol(kPaused)]: null }, _events: [Object: null prototype] { end: [Function: clearRequestTimeout] }, _eventsCount: 1, _maxListeners: undefined, socket: lt;ref *1gt; Socket { connecting: false, _hadError: false, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Array], timeout: [Function: socketOnTimeout], data: [Function: bound socketOnData], error: [Function: socketOnError], close: [Array], drain: [Function: bound socketOnDrain], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 8, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 0, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: false, errored: null, closed: false, closeEmitted: false }, allowHalfOpen: true, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '4:127.0.0.1:3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 11 }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '4:127.0.0.1:3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 11 }, parser: HTTPParser { '0': [Function: bound setRequestTimeout], '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], _sent100: false, _expect_continue: false, req: [Circular *2], locals: [Object: null prototype] {}, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] }, timeout: 0, [Symbol(async_id_symbol)]: 20, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: Timeout { _idleTimeout: -1, _idlePrev: null, _idleNext: null, _idleStart: 2049, _onTimeout: null, _timerArgs: undefined, _repeat: null, _destroyed: true, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 28, [Symbol(triggerId)]: 24 }, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: false, headers: { host: '127.0.0.1:3000', connection: 'keep-alive', 'content-length': '66', 'sec-ch-ua': '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"', accept: 'application/json, text/plain, */*', 'content-type': 'applcation/json', 'sec-ch-ua-mobile': '?0', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36', 'sec-ch-ua-platform': '"Linux"', origin: 'http://localhost:4200', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', referer: 'http://localhost:4200/', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9' }, rawHeaders: [ 'Host', '127.0.0.1:3000', 'Connection', 'keep-alive', 'Content-Length', '66', 'sec-ch-ua', '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"', 'Accept', 'application/json, text/plain, */*', 'Content-Type', 'applcation/json', 'sec-ch-ua-mobile', '?0', 'User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36', 'sec-ch-ua-platform', '"Linux"', 'Origin', 'http://localhost:4200', 'Sec-Fetch-Site', 'cross-site', 'Sec-Fetch-Mode', 'cors', 'Sec-Fetch-Dest', 'empty', 'Referer', 'http://localhost:4200/', 'Accept-Encoding', 'gzip, deflate, br', 'Accept-Language', 'en-US,en;q=0.9' ], trailers: {}, rawTrailers: [], aborted: false, upgrade: false, url: '/', method: 'POST', statusCode: null, statusMessage: null, client: lt;ref *1gt; Socket { connecting: false, _hadError: false, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Array], timeout: [Function: socketOnTimeout], data: [Function: bound socketOnData], error: [Function: socketOnError], close: [Array], drain: [Function: bound socketOnDrain], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 8, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 0, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: false, errored: null, closed: false, closeEmitted: false }, allowHalfOpen: true, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '4:127.0.0.1:3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 11 }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 1, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '4:127.0.0.1:3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 11 }, parser: HTTPParser { '0': [Function: bound setRequestTimeout], '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], _sent100: false, _expect_continue: false, req: [Circular *2], locals: [Object: null prototype] {}, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] }, timeout: 0, [Symbol(async_id_symbol)]: 20, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: Timeout { _idleTimeout: -1, _idlePrev: null, _idleNext: null, _idleStart: 2049, _onTimeout: null, _timerArgs: undefined, _repeat: null, _destroyed: true, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 28, [Symbol(triggerId)]: 24 }, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, _consuming: false, _dumped: false, next: [Function: next], baseUrl: '', originalUrl: '/', _parsedUrl: Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/', path: '/', href: '/', _raw: '/' }, params: {}, query: {}, res: lt;ref *3gt; ServerResponse { _events: [Object: null prototype] { finish: [Function: bound resOnFinish] }, _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: lt;ref *1gt; Socket { connecting: false, _hadError: false, _parent: null, _host: null, _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 8, _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: true, _sockname: null, _pendingData: null, _pendingEncoding: '', server: [Server], _server: [Server], parser: [HTTPParser], on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], _paused: false, _httpMessage: [Circular *3], timeout: 0, [Symbol(async_id_symbol)]: 20, [Symbol(kHandle)]: [TCP], [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: Timeout { _idleTimeout: -1, _idlePrev: null, _idleNext: null, _idleStart: 2049, _onTimeout: null, _timerArgs: undefined, _repeat: null, _destroyed: true, [Symbol(refed)]: false, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 28, [Symbol(triggerId)]: 24 }, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], _sent100: false, _expect_continue: false, req: [Circular *2], locals: [Object: null prototype] {}, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] { 'x-powered-by': [Array], 'access-control-allow-origin': [Array], vary: [Array] } }, body: {}, route: Route { path: '/', stack: [ [Layer] ], methods: { post: true } }, [Symbol(kCapture)]: false, [Symbol(RequestTimeout)]:
Итак, вот мой вопрос: как мне получить параметры записи в NodeJS?
Комментарии:
1. Вы уверены, что вам нужны параметры? Я предполагаю, что «параметры публикации» = тело запроса? Если
req.body
бы это было то, чего вы хотите, и нетreq.params
.2. Покажите свой код на стороне клиента
3. Я не знаю, какую библиотеку вы используете для выполнения запроса на публикацию, но вам, вероятно, следует указать тип контента.
application/x-www-form-urlencoded
было бы для обычных почтовых параметров. json для json, как упоминал @JastriaRahmat.4. укажите тип содержимого для application/json. затем, в express, журнал консоли(req.тело)
5. @NewUser2 на будущее —
*
это довольно бессмысленно. По сути, вы говорите серверу, что «запрос может содержать что угодно», всегда лучше быть явным.application/json
например.
Ответ №1:
Как и в комментариях, на стороне клиента вам нужно указать content type
явно.
например:
'Content-Type': 'application/json'
затем в вашем экспресс-приложении:
console.log(req.body)
кредиты @isolated и @john в комментариях к вопросу
Комментарии:
1. Небольшая деталь, на которую я не обратил внимания, особенно потому, что она работала с PHP, ха-ха. Но спасибо всем вам @John, Изолированным и вам.