Не удается получить параметры сообщения в экспрессе

0

Мой угловой почтовый индекс:

    userModule.controller('registrationController', function($scope, $http){
    $scope.Name = "";
    $scope.Email = "";
    $scope.Password = "";
    $scope.Repeat = "";
    $scope.register = function () {
        if ($scope.Name.length == 0){
            swal("Please enter your name!", "", "error");
            return;
        }
        if ($scope.Email.length == 0){
            swal("Please enter your email!", "", "error");
            return;
        }
        if ($scope.Password.length == 0){
            swal("Please enter your password!", "", "error");
            return;
        }
        if ($scope.Password !== $scope.Repeat){
            swal("Passwords do not match!", "", "error");
            return;
        }

        var data = $.param({
            Name: $scope.Name,
            Email_id: $scope.Email,
            Password: $scope.Password
        });

        var config = {
            headers : {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        };

        $http.post("http://localhost:8000/register", data, config).then
        (
            //Success Callback
            function (res) {
                /*if (res.data.Status == 1)
                    swal("Success", res.data.Message, "success");
                else
                    swal("Error", res.data.Message, "error");

                $scope.Name = null;
                $scope.Email = null;
                $scope.Password = null;
                $scope.Repeat = null;*/
                alert(res.data.success);
            },
            //Error Callback
            function () {
                $scope.registrationResponse = "";
                swal("Request couldn't be sent!", "", "error");
            }
        );
    };
});

Экспресс:

1) app.js:

var bodyParser  = require("body-parser");
var express = require('express');

var app = express();
var port = 8000;

app.use('/', express.static('./style'));
app.use('/', express.static('./node_modules'));
app.use('/', express.static('./js'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

require('./server/routes')(app);

app.listen(port, function(error, response){
    if (error){
        console.log("Failed to run server!");
    }
});


module.exports = app;

2) route/index.js:

module.exports = function (app) {

    app.get('/', function (req, res) {
        res.sendFile('index.html', {root:'./view/'});
    });

    app.get('/index', function(req, res){
        res.sendFile('index.html', {root:'./view/'});
    });

    app.post('/login', function(req, resp){
        resp.json({"success":"OK"});
    });

    app.post('/register', function(req, resp){
        //registerUser(req.body.params);
        console.log(req.headers);
        console.log(req.body);
        resp.json({"success":"OK"});
    })
};

Я также пробовал: req.params, req.query и все они пустые. Что я делаю не так?

вывод:

req.header:

{ host: 'localhost:8000',
  connection: 'keep-alive',
  'content-length': '48',
  accept: 'application/json, text/plain, */*',
  origin: 'http://localhost:8000',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 OPR/38.0.2220.31',
  'content-type': 'application/x-www-form-urlencoded;charset=UTF-8;',
  dnt: '1',
  referer: 'http://localhost:8000/',
  'accept-encoding': 'gzip, deflate, lzma',
  'accept-language': 'en-US,en;q=0.8' }

req.body:

undefined

Полный резервный резерв:

IncomingMessage {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: true,
     ended: true,
     endEmitted: true,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: false,
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  socket:
   Socket {
     _connecting: false,
     _hadError: false,
     _handle:
      TCP {
        _externalStream: {},
        fd: -1,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        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: true,
        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,
     bytesRead: 0,
     _bytesDispatched: 0,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _idleTimeout: 120000,
     _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idleStart: 3484,
     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,
        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 {
        _externalStream: {},
        fd: -1,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        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: true,
        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,
     bytesRead: 0,
     _bytesDispatched: 0,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _idleTimeout: 120000,
     _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idleStart: 3484,
     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,
        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: true,
  headers:
   { host: 'localhost:8000',
     connection: 'keep-alive',
     'content-length': '47',
     accept: 'application/json, text/plain, */*',
     origin: 'http://localhost:8000',
     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 OPR/38.0.2220.31',
     'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
     dnt: '1',
     referer: 'http://localhost:8000/',
     'accept-encoding': 'gzip, deflate, lzma',
     'accept-language': 'en-US,en;q=0.8' },
  rawHeaders:
   [ 'Host',
     'localhost:8000',
     'Connection',
     'keep-alive',
     'Content-Length',
     '47',
     'Accept',
     'application/json, text/plain, */*',
     'Origin',
     'http://localhost:8000',
     'User-Agent',
     'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 OPR/38.0.2220.31',
     'Content-Type',
     'application/x-www-form-urlencoded;charset=UTF-8',
     'DNT',
     '1',
     'Referer',
     'http://localhost:8000/',
     'Accept-Encoding',
     'gzip, deflate, lzma',
     'Accept-Language',
     'en-US,en;q=0.8' ],
  trailers: {},
  rawTrailers: [],
  upgrade: false,
  url: '/register',
  method: 'POST',
  statusCode: null,
  statusMessage: null,
  client:
   Socket {
     _connecting: false,
     _hadError: false,
     _handle:
      TCP {
        _externalStream: {},
        fd: -1,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        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: true,
        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,
     bytesRead: 0,
     _bytesDispatched: 0,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _server:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::8000' },
     _idleTimeout: 120000,
     _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idleStart: 3484,
     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,
        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: true,
  _dumped: false,
  next: [Function: next],
  baseUrl: '',
  originalUrl: '/register',
  _parsedUrl:
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: null,
     pathname: '/register',
     path: '/register',
     href: '/register',
     _raw: '/register' },
  params: {},
  query: {},
  res:
   ServerResponse {
     domain: null,
     _events: { finish: [Function: resOnFinish] },
     _eventsCount: 1,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: 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,
        bytesRead: 0,
        _bytesDispatched: 0,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3484,
        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,
        bytesRead: 0,
        _bytesDispatched: 0,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3484,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     _header: null,
     _headers: { 'x-powered-by': 'Express' },
     _headerNames: { 'x-powered-by': 'X-Powered-By' },
     _onPendingData: [Function: updateOutgoingData],
     req: [Circular],
     locals: {} },
  body: { Name: 'asd', Email_id: '[email protected]', Password: '12345' },
  _body: true,
  length: undefined,
  read: [Function],
  route:
   Route {
     path: '/register',
     stack: [ [Object] ],
     methods: { post: true } } }
  • 0
    все ваши console.log() находятся в /register , но ваш код публикуется в /login .
  • 0
    Я вставил неправильный код. Сожалею! * Исправленный *
Показать ещё 3 комментария
Теги:
express

3 ответа

0

Для express и использования body-parser, когда вы вызываете req.params, это относится к параметрам URL, которые передаются в соответствии с вашими спецификациями маршрута.

Например, если у меня есть определенный маршрут:

/* User goes to /sample/example */
app.get('/sample/:value', (req, res) => {
    var value = req.params.value;
});

Тогда value переменной содержит example строки.

Чтобы получить тело запроса POST в express, вы используете req.body.# - где # - это ключ в данных POST json. Таким образом, в случае вашего json, req.body.connection вернется в req.body.connection keep-alive.

  • 0
    часть, которую вы видите в выводе, является заголовком запроса. «неопределенный» - это тело. В моем случае req.body.Name должно показывать имя, которое я передаю. Его показ как неопределенный.
0

Вы можете попробовать зарегистрировать весь объект req, и я уверен, вы не увидите никаких параметров. Я подозреваю, что вы читаете их правильно, но их там нет - они не отправляются должным образом или каким-то образом их отфильтровывают, прежде чем они достигнут вашего маршрута.

Вы можете проверить эту гипотезу, используя бесплатный инструмент, такой как Postman, для отправки запроса POST в ваше приложение с вашими желаемыми параметрами в правильном формате (json/form).

  • 0
    Я добавил полный дамп запроса. Формат не JSON. Его приложение / x-www-form-urlencoded; charset = utf-8
0

Недопустимый заголовок типа контента:

'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'

Конечной точки с запятой не должно быть, поэтому должно быть так:

'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  • 0
    не помогает Я все еще становлюсь неопределенным.
  • 0
    @Priyabrata, который предположил бы, что промежуточное программное обеспечение анализатора тела вообще не получает запрос. Требуется ли require('./server/routes')(app) (в конечном итоге) загрузить route/index.js ?
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню