Search code examples
pythonjsonangularflaskangular2-services

Making an Angular2 POST with JSON


I have a simple Flask backend for the API, and want to make a POST. I'm not sure the error is-I get the error message, but am unsure if its an Angular or Flask issue. I tried request.get_json() in my Flask, and got

{BadRequest}400 BadRequest: The browser (or proxy) sent a request that this server could not understand

Angular2 call in my service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable} from 'rxjs/Rx';
import { Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class NicksService {

  private headers = new Headers({'Content-Type': 'application/json'});
  nickUrl: string = "http://localhost:5000/nick";
  constructor(private http: Http) { }

  // Send the nick to the server to see if it is valid
  checkNickValidity(nickName: string): Observable<string>{

    return  this.http.post(this.nickUrl, JSON.stringify({nick: nickName}), {headers: this.headers})
    .map(this.extractData)
    .catch(this.handleError)
  }

Flask backend:

from flask_cors import CORS
from flask.ext.api import FlaskAPI
from flask import request

app = FlaskAPI(__name__)
CORS(app)


@app.route('/')
@app.route('/nick', methods=['POST'])
def check_nick():

    try:
        nick = request.json
        if nick =='AmandaPanda':
            return 'Good'
        else:
            return 'No nick found'
    except:
        return 'error'



if __name__ == '__main__':
    app.run()

Solution

  • I think you have problems on both sides of your application.

    Client side:

    Angular's Http's post method receives any object in for the body parameter, meaning you don't need to stringify it.

    E.g.:

    this.http.post(this.nickUrl, {nick: nickName}, {headers: this.headers})
    

    Server side:

    Once the client's request arrived properly to the server, you are not getting the data properly.

    What you need to do is something like this:

    from flask import jsonify
    
    (... your code ...)
    
        data = request.json
        nick = data.get('nick')
        if nick == 'AmandaPanda':
            return jsonify({'message': 'good'}), 200
        else:
            return jsonify({'message': 'no nick found'}), 400
    

    Here, the json data is stored as a dictionary in the variable data. Later, the nick is obtained from the nick key of said dictionary.

    Finally, it is a better practice to return to the client in json form. That's what Flask's jsonify method is for. Notice the 200 and 400 status codes appended to the response, to indicate to the client if the request was properly accepted (200) or if it was a bad request (400).