简体   繁体   中英

Angular 2 Post Request to Node/Express Server Endpoint

I can't seem to diagnose why I can't send a successful HTTP request in my Angular 2 Typescript application. I send POST requests successfully through Postman, but the front-end seems to be unhappy about linking to the back-end... there's no error, and the back-end never responds. Please help!

I'm working in a C9 environment.

Here's my current implementation:

import {Component} from 'angular2/core';
import {MessageBody} from '../message-body/message-body';
import {Http, HTTP_PROVIDERS, Headers} from 'angular2/http';

@Component({
  selector: 'signup',
  template: require('app/signup/signup.html'),
  styles: [require('app/signup/signup.css')],
  viewProviders: [HTTP_PROVIDERS],
  providers: []
})

export class Signup {
  model = new MessageBody(
    '',
    '',
    '',
    '');
  constructor(public http: Http) {
  }
  onSubmit() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.http.post('/email', JSON.stringify(this.model), {headers: headers})
      .map(res => console.log(res.json()));
  }
}

This is the endpoint on the server:

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/email', sendEmail);

app.use(express.static(__dirname +'/../dist'));

app.listen(process.env.PORT, listen);

I've tried posting to /email , http://localhost:8080/email , https://{appName}-{username}.c9users.io/email , all to no avail!

What am I doing wrong? I appreciate the help!

EDIT: Thierry already answered here, so this is a dupe. angular2: http post not executing

There is a mismatch between the content type and the content you provide to the POST method.

If you expect url-encoded form, you need to update your code this way:

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

  var content = new URLSearchParams();
  content.set('somefield', this.model.somefield);
  (...)

  this.http.post('/email', content.toString(), {headers: headers})
  .map(res => console.log(res.json()));
}

If you want to send JSON content, just change the value of the Content-Type header:

onSubmit() {
  var headers = new Headers();
  headers.append('Content-Type', 'application/json');

  this.http.post('/email', JSON.stringify(this/model), {headers: headers})
  .map(res => console.log(res.json()));
}

Moreover I think that you endpoint isn't located on the same machine unless you serve it through your Express application with something like this:

app.use(express.static('public'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM