Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

415 (Unsupported Media Type) angular 4 Post

I am trying to access a wep api with angular 4 post method.

In my service, I've added content-type of application/json. And I'm converting the object into json while sending data to api. I am using HttpClientModule

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()

export class NewServiceService {

  baseUrl = "http://localhost:33969/api/";
  headers = { headers: new Headers({ 'Content-Type': 'application/json' }) 
      };
  obj= {
    name:"A",
    cgpa: 3
  };

_http:any;
constructor(http: HttpClient) {
    this._http = http;
}

SaveStudents(){

    this._http
    .post(
        this.baseUrl + 'home/Save', 
        JSON.stringify(this.obj),
        this.headers
     )
  .subscribe(
    res => {
      alert("Student Saved!");
    },
    err => {
      alert("Error!");
    }
  );
}}

In the API,

using Entity;
using Microsoft.AspNetCore.Mvc;
using Repo;

namespace API_Core.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]

public class HomeController : Controller
{
    IStudent _student;
    public HomeController(IStudent student)
    {
        _student = student;
    }

    [HttpPost]   
    public Student Save([FromBody]Student s)
    {
        return _student.Save(s);
    }
}
}

here, I want to catch the objtect as Student model and do something with the data. Here is the Student Model

public class Student
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public double Cgpa { get; set; }
}

But when using prostman, I could succesfully receive the object.enter image description here

UPDATE using HttpHeaders instead of Headers and CORS solved the issue

Enabling CORS for ASP.NET Core 2 =>

In ConfigureServices:

services.AddCors(options => options.AddPolicy("Cors", builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
        }));

In Configure(Above usemvc()):

app.UseCors("Cors");
like image 877
Jaowat Raihan Avatar asked Apr 09 '18 05:04

Jaowat Raihan


2 Answers

You need to change the below line

  headers = { headers: new Headers({ 'Content-Type': 'application/json' }) 
      };

to

headers={
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
    })
}
like image 164
Thangadurai Avatar answered Nov 11 '22 11:11

Thangadurai


In my case the 415 error was caused because I was calling JSON.stringify(obj) when there was no need for it. I read somewhere that post method will stringify the body parameter as needed

So instead of this:

this._http
.post(
    this.baseUrl + 'home/Save', 
    JSON.stringify(this.obj),
    this.headers
 )

I changed it to this:

this._http
.post(
    this.baseUrl + 'home/Save', 
    this.obj, // << no need to stringify 
    this.headers
)

Here is my actual working code

@Injectable()
export class ParkingService {
  constructor(private http: HttpClient) { }

  create(parking: Parking) {
    const requestUrl = environment.apiUrl + 'parking' ;
    const headerOptions = new HttpHeaders();

    headerOptions.set('Content-Type', 'application/json');
    return this.http.post(requestUrl, parking, {headers: headerOptions}) ;
  }
}

This happened to me even after enabling and configuring CORS on the .NET core web api

like image 26
Mauricio Gracia Gutierrez Avatar answered Nov 11 '22 10:11

Mauricio Gracia Gutierrez