0

I use Bottle for my backend and Angular2 for my frontend. When using POST request I would like to return a response, but for some reason, it doesn't return response

Python code:

@app.post("/api/post/new_post")
def hp_new_post():
    pd = json.loads(request.body.read().decode("utf-8"))
    try:
        cl.eduo.posts.insert_one(
            {
                "h": pd['h'],
                "d": pd['d'],
                "t": pd['t']
            }
        )
    except Exception:
        response.status = 500
    response.content_type = 'application/json'
    response.status = 200
    return response

Angular code:

var result = from(
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(
        {
          "h": h,
          "d": des,
          "t": Date.now()
        }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
).subscribe(
  {
    next(data) {
      console.log(data);
    },
    error(msg) {
      console.log(msg);
    }
  }
)

When I console.log data from a request I get:

body: null
bodyUsed: false
headers: Headers {  }   
ok: false    ​
redirected: false    ​
status: 0    ​
statusText: ""    ​
type: "opaque"    ​
url: ""
Jakov Gl.
  • 361
  • 3
  • 11
  • 1
    Looks like this is more on the server (python) side than angular. Have you tried configuring cors in your python app? Might be helpful to read through some these answers: https://stackoverflow.com/questions/36292537/what-is-an-opaque-response-and-what-purpose-does-it-serve – mwilson Mar 24 '20 at 17:49

1 Answers1

1

I recommend you to use HttpClient. For that, import HttpClientModule, and your code could be :

constructor(private httpClient: HttpClient) {}

load() {
  this.http.post(this.baseurl, {
    "h": h,
    "d": des,
    "t": Date.now()
  }, { 
    observe: 'response',
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    }
  }).subscribe(response => {

    // do stuff with body
    // response.body

    // this will output headers received
    const keys = response.headers.keys();
    const headers = keys.map(key =>
    `${key}: ${response.headers.get(key)}`);

     console.table(headers);
  })
}

If you don't need response details, but only body received :

this.http.post<MyData>(this.baseurl, {
  "h": h,
  "d": des,
  "t": Date.now()
}).subscribe(data => {
  // do stuff with data of type MyData
  data.name...
}); 

More details on Angular official docs.

Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39