Sending JSON object data to an API endpoint using the POST method in an Angular application

Attempted to post data to an API, but received a 400 bad request error. After testing with Postman, it seems that the issue may lie within my service or TypeScript code. As a newcomer to Angular, I am seeking assistance as I have searched extensively without finding a solution. The API expects values in JSON format (Note: using Angular4 Web API).

{ 
 "Header": {
        "UserID": 6,
       "created": "February 4, 2016 10:13:00",
        ....etc........
     },
  "detail": [
{
  "ShopID": 1,
 "ItemID": 126,
.....etc.........
  },
  {     
 "ShopID": 1,
 "ItemID": 127,
.....etc.........
 }
 ]
 }

Data being passed to the API looks like this (potentially causing the problem):

    [{
  "userid": "64",
  "created": "February 4, 2016 10:13:00",
  "CompanyID": "1",
  "modified": "February 4, 2016 10:13:00",
  "modifieduserid": "65",
  "confirm": "true",
  "ShopId": 1,
  "TransactionId": 1,
   "shopid": 12,
  "Itemid": 12928,
  "PackingTypeID": 3,
  "Itemcode": "124018",
  "Itemdescription": "COTTON GLOVES 350G",
  "PackingtypeName": "12 PCS",
  "Stockcount": 12

}

This is my TypeScript file:

     stockitems: IStockCountHeaders[] = [];   
 items: IStockCountHeaders;
  stockdetail: IStockdetails[] = [];

  addItems(value: any) {
this.items = new IStockCountHeaders(this.userid, this.created, t this.confirm,this.shopid, 
 value.ItemID, value.PackingTypeID, value.ItemCode, value.ItemDescription, 
 value.PackingtypeName, 
    value.Stock,
   );
this.stockitems.push(this.items);
  }
onclick(){
 this._enqService.CatchStockDetailHeader(this.stockitems)
    .subscribe(value => {
        if (typeof value !== 'undefined' && value != null) {
            value.forEach(items => {
                this.stockitems.push(this.items)
            });
        }
    },
        error => {
            console.error(error);
            this.statusMessage = "Problem with the service.Please try again after sometime";
        });
 }

This is my Angular service file:

          CatchStockDetailHeader(stock: any)
    : Observable<IStockCountHeaders[]> {
    let IStockCounts = stock;  
    console.log(IStockCounts)
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    headers.append('userid', IStockCounts.userid);
    headers.append('created', IStockCounts.created);
    headers.append('.CompanyID', IStockCounts.CompanyID);
    headers.append('modified', IStockCounts.modified);
    headers.append('modifieduserid', IStockCounts.modifieduserid);
    headers.append('confirm', IStockCounts.confirm);    
    return this._http.post('http://localhost:3071/api/Stockcountheader/' + 'Stock', IStockCounts, options)
        .map((response: Response) => <IStockCountHeaders[]>response.json())
        .catch(this.handleError);
}

Answer №1

Your current situation involves sending a cross-domain request as you are submitting to localhost:3071 while your Angular app is typically hosted on localhost:4200.

You have two choices: either include an allow all header from the API or employ a proxy.

To permit cross-domain requests from your API, include the following header

Access-Control-Allow-Origin: *

on the server side.

If opting for a proxy, create a file named proxy.config.json

{
  "/api/*": {
    "target": "http://localhost:3071/api/",
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

and run it using

ng serve --proxy-config proxy.config.json

Instead of accessing

http://localhost:3071/api/

access

/api/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a functioning implementation for retrieving a list of objects from a REST API

I am looking to incorporate an Angular example that retrieves a list from a REST API. Here is what I have attempted: SQL query: @Override public Iterable<Merchants> findAll() { String hql = "select e from " + Merchants.class.getName ...

What is the significance of an empty href attribute in the HTML <base> tag?

If my website URL is: http://example.com/path/to/dir/index.html And I decide to proxy this page through: http://proxyserver.com/path/to/dir/index.html. I would like all relative URLs on the page to be resolved by proxyserver.com instead of example.com. Wh ...

Retrieve the parent injector passed to the component during testing

My approach to obtaining an injector is as follows: constructor( private injector: Injector, ) {} Afterwards, I proceed to create a new injector and utilize the current one as its parent (specifically when opening a material dialog, though this detail ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

The primary route module is automatically loaded alongside all other modules

I have configured my lazy loaded Home module to have an empty path. However, the issue I am facing is that whenever I try to load different modules such as login using its URL like /new/auth, the home module also gets loaded along with it. const routes: R ...

Update the data and paginator status

In my development project, I have implemented PrimeNG Turbotable with the code <p-table #dt. Based on information from here, using dt.reset() will clear the sort, filter, and paginator settings. However, I am looking for a solution to only reset the pa ...

How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created: @Component ({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.css'] }) export class ProgressBarComponent ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

Error: The archived-solution-list.component.html file failed to load due to an unhandled Promise rejection

I am encountering the following error on the console while executing my code. Just so you know, everything was working fine before a minor modification. I would appreciate your assistance in resolving this: Unhandled Promise rejection: Failed to load ar ...

Is it possible to postpone the initiation of an Angular application until a promise is fulfilled

At the moment, my code looks like this: new Loader().load().then(() => { platformBrowserDynamic().bootstrapModule(AppModule); }); The issue lies in the fact that I only need to delay the execution of ngOnInit and any route resolving until a prom ...

switching the content of a button when it is clicked

I am currently using Angular 7 and I am trying to achieve a functionality where the text on a button changes every time it is clicked, toggling between 'login' and 'logout'. Below is the code snippet I have been working on: typescript ...

Form submission resulting in 405 error

Currently, I am facing an issue while trying to send data to the server. The PHP side seems to be functioning correctly as the post request is successful when tested using Postman. However, when attempting to do so from Angular, I encounter a 405 (Method N ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

https://i.sstatic.net/j76vM.pnghttps://i.sstatic.net/EQPZO.png I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...

Setting up a Node.js project in your local environment and making it

I need help installing my custom project globally so I can access it from anywhere in my computer using the command line. However, I've been struggling to make it work. I attempted the following command: npm install -g . and some others that I can&ap ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

Consider a scenario where we have a class A and its subclass B. The goal is to assign an array of instances of class B to an array of instances of class A. While this works with normal arrays, the same operation fails when using ko.ObservableArray. import ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...