Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 http.post and undefined req.body

I have a problem with receiving json from http.post. Let's make it clear a bit: This is my component file:

import {Component} from 'angular2/core'
import {Http, HTTP_PROVIDERS, Headers} from 'angular2/http'

@Component({
  selector: 'login-form',
  template: `
    <form (ngSubmit)="onSubmit()">

      <button type="submit">Wyslij</button>
    </form>
  `
})

export class LoginFormComponent {
  constructor(public http: Http) { }

  onSubmit() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var data = JSON.stringify({
      login: "zupa",
    });

    this.http.post('http://localhost:8080/send', data, {headers: headers})
    .subscribe();
  }
}

My server.js file

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'node_modules')));
app.use(express.static(path.join(__dirname)));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

app.get('*', function(req, res, next) {
  res.render("index.html", {title: 'Aplikacja'});
});

app.listen(8080, function() {
  console.log("Starting at localhost:8080");
});

module.exports = app;

As you can see, this is a standard generated by express module server file.

This is content of my "routes" file.

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index.html', {title: 'Infam'});
});

router.post('/send', function(req, res, next) {
  console.log("Received data: " + req.body.login);
});

module.exports = router;

The server returns a message to me: "Received data: undefined" and I have no idea why the req.body.login is undefined. Can you help me? Thank you in advance.

PS: The same is when I use

"login": "zupa"

instead of

login: "zupa"
like image 893
elzoy Avatar asked Jan 13 '16 14:01

elzoy


People also ask

How to use HTTP POST () method in Angular 2?

On this page we will provide angular 2 Http post () example. It performs a request using HTTP POST method. In Http.post () method, we need to pass server URL, any object to post and request option that is optional. In request option we can set request headers such as content type and to handle this angular provides Headers and RequestOptions API.

How to handle HTTP error in angular?

Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor. Suggested Reading: Error Handling in Angular

How to test HTTP methods in angular in memory?

Angular provides in-memory web API to process HTTP request in test environment. In case we don't have actual server URL, we can use angular in-memory web API for testing our angular Http methods. It provides a dummy URL that can be replaced by actual REST web service URL later.

How to process HTTP request in test environment in angular?

Http.post () 1 Step-1::. 2 Step-2::. This approach is preferable by design. In a service class we will use dependency injection to get the instance... 3 Step-3::. Angular provides in-memory web API to process HTTP request in test environment. In case we don't have actual... More ...


1 Answers

You should set the appropriate headers since you are using JSON.

headers.append('Content-Type', 'application/json');
like image 156
Simone Zandara Avatar answered Oct 10 '22 02:10

Simone Zandara