0
votes

I am busy with a small web app where I am trying to post to a API using a RestService but keep getting a 400 bad request. When I do the exact same post using the Insomnia Rest client I get a 200 Ok... Any idea what i'm doing wrong/what I can look at to find out what's going on?

Update: It turns out the issue is a incorrect header, there's still a unresolved error i'm getting when trying to add the correct header... Question continuation link Here

My error:

http://10.60.160.34/BRMServices/WebEnquiry/StockTake/AddToStockTake Failed to load resource: the server responded with a status of 400 (Bad Request) stockTake:1 XMLHttpRequest cannot load http://10.60.160.34/BRMServices/WebEnquiry/StockTake/AddToStockTake. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 400. main.bundle.js:47711 failure: server error

My code:

stock-take.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { RestService } from '../../services/rest.service';

import { StockTakeModel } from '../../models/stock-take.model';

@Component({
  selector: 'stock-take',
  templateUrl: './stock-take.component.html',
  styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
    stockTakeForm: FormGroup;
    stockTakeModel: StockTakeModel;

  constructor(private fb: FormBuilder, private restService: RestService) { 
    this.stockTakeForm = fb.group({
        'SheetNo':['', Validators.required],
        'BinNo':['', Validators.required],
        'BarCode':['', Validators.required],
        'Quantity':['', Validators.required]
    });
    }

    doStockTake(val: any) {
        //console.log("val:" + JSON.stringify(val));
        //this.stockTakeModel = new StockTakeModel(0, 0, val[Object.keys(val)[2] '', val[Object.keys(val)[0]], val[Object.keys(val)[1]], val[Object.keys(val)[3]], 0);
        this.stockTakeModel = val;
    this.stockTakeModel.StockTakeID = '0';
    this.stockTakeModel.IDKey = '0';    
    this.stockTakeModel.ProductCode = '';
    this.stockTakeModel.PackSize = '0';
    console.log(this.stockTakeModel);
    console.log(JSON.stringify(this.stockTakeModel));
    this.submitStockTake(this.stockTakeModel);
    }

  submitStockTake(stockTakeModel: StockTakeModel) {
      //console.log(stockTakeModel);

    this.restService.postStockTake(stockTakeModel)
    .subscribe(
    (res) => {
        console.log(res);
    },
    (res) => {
        console.log("failure: " + res);
    }
    );
    this.stockTakeForm.reset();
  }

  ngOnInit() {

  }

}

submitStockTake function from rest.service.ts:

postStockTake(stockTakeModel: StockTakeModel) : Observable<Response> {
      console.log(JSON.stringify(stockTakeModel));

        return this.http.post(this.API_URL + "StockTake/AddToStockTake", JSON.stringify(stockTakeModel), this.headers)
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'server error'));
  }
4
Now looking at your previous question... you should anyway use this.options instead of this.headers in your post request. And your rest api is actually accepting POST request and not GET? Just checking ;)AJT82
No it's accepting get requests but not post. I tried to use get with requestOptions before and had the same issue. Sorry for the confusion...user2094257
Well, you have to make sure your rest is accepting post, and not get. That would of course cause an error if rest is accepting get instead of post. And do change this.headers to this.options instead.AJT82
When you are sending a get request, rest needs to have get as well. And when you are sending post, rest has to have post as well. Otherwise it won't work.AJT82
It works fine when using the Insomnia Rest client... So it can't be the API... I had the exact same issue in the past when using RequestOptions with my working get requests. This is the first Post request I have to do for this app and can't think of any way of getting around using RequestOptions anymore...user2094257

4 Answers

0
votes

That indicates that you are not quite posting the same thing both ways - perhaps different request headers? Perhpas the browser running RestClient has authenticated? Inspect the actual requests in the network tab and check URL, headers, authentication etc - something has to be different.

0
votes

Looking into things... here: angular.io http

it seems you aren't supposed to stringify (anymore), so try:

postStockTake(stockTakeModel: string) : Observable<Response> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

      return this.http.post(this.API_URL + "StockTake/AddToStockTake", { stockTakeModel }, options)
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'server error'));
  }
0
votes

You should authorise the header "Authorization" on your server side

0
votes

I have also faced this issue and resolved it by removing proxy. Please check if you have set any proxy.