как исправить ошибку 404 в угловых 7, хотя URL-адрес правильный - PullRequest
0 голосов
/ 01 апреля 2019

Я пытаюсь отправить запрос на публикацию на моем сервере Java Rest, и он отлично работает с 10 URL-адресами, но теперь по какой-то причине я получаю сообщение об ошибке 404 по указанному мною URL-адресу и проверил его в Fiddler, и он работаетхорошо.моя цель - иметь возможность отправить мой объект JSON на мой сервер, но по какой-то причине я получаю сообщение об ошибке 404.

Это служба с URL-адресами, которые не работают:

    import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Coupon } from '../Entities/coupon';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CompanyService {

  private CrtCouponURL = 'http://localhost:8080/CouponSystemWeb/rest/company/CrtCoupon'
  private RmvCouponURL ='http://localhost:8080/CouponSystemWeb/rest/company/RmvCoupon'
  private UpdtCouponURL ='http://localhost:8080/CouponSystemWeb/rest/company/UpdtCoupon'
  private GetAllCouponURL ='http://localhost:8080/CouponSystemWeb/rest/company/GetAllCoupons'
  private couponByTypeURL ='http://localhost:8080/CouponSystemWeb/rest/company/TypeCouponsGet'
  constructor(private http:HttpClient){ }

public createCoupon(coupon:Coupon):Observable<Coupon>{
  return this.http.post<Coupon>(this.CrtCouponURL, coupon ,{withCredentials:true})
}
public deleteCoupon(id:number):Observable<Coupon>{
  return this.http.delete<Coupon>(this.RmvCouponURL+'/?id='+id,{withCredentials:true})
}
public updateCoupon(coupon:Coupon):Observable<Coupon>{
  return this.http.put<Coupon>(this.UpdtCouponURL,coupon,{withCredentials:true})
}
public getAllCoupons():Observable<Coupon[]>{
  return this.http.get<Coupon[]>(this.GetAllCouponURL,{withCredentials:true})
}
public getAllCouponsByType(type:string):Observable<Coupon[]>{
  return this.http.get<Coupon[]>(this.couponByTypeURL+'/?type='+type,{withCredentials:true})
}
}

Это сервис с URL-адресами, которые действительно работают:

@Injectable({
  providedIn: 'root'
})
export class AdminService {
  private companyUrl = 'http://localhost:8080/CouponSystemWeb/rest/admin/company'
  private customerUrl = 'http://localhost:8080/CouponSystemWeb/rest/admin/customer'
  private companyCrtUrl = 'http://localhost:8080/CouponSystemWeb/rest/admin/companyCrt'
  private updateCompURL = 'http://localhost:8080/CouponSystemWeb/rest/admin/UpdateComp'
  private customerCrtUrl = 'http://localhost:8080/CouponSystemWeb/rest/admin/CreateCustomer'
  private customerDelUrl = 'http://localhost:8080/CouponSystemWeb/rest/admin/RmvCustomer'
  constructor(private http: HttpClient) { }

  public createCompany(company: Company): Observable<Company> {
    return this.http.post<Company>(this.companyCrtUrl, company, { withCredentials: true })
  }
  public deleteCompany(id: number): Observable<Company> {
    return this.http.delete<Company>("http://localhost:8080/CouponSystemWeb/rest/admin/mycompany/" + id, { withCredentials: true })
  }
  public updateCompany(id: number, company: Company): Observable<Company> {
    company.id = id;
    return this.http.put<Company>(this.updateCompURL, company, { withCredentials: true })
  }
  public getCompany(id: number): Observable<Company> {
    return this.http.get<Company>(this.companyUrl + "?=id" + id, { withCredentials: true })
  }
  public getAllCompanies(): Observable<Company[]> {
    return this.http.get<Company[]>(this.companyUrl, { withCredentials: true })
  }
  public createCustomer(customer: Customer): Observable<Customer> {
    return this.http.post<Customer>(this.customerCrtUrl, customer, { withCredentials: true })
  }
  public deleteCustomer(id: number): Observable<Customer> {
    return this.http.delete<Customer>(this.customerDelUrl + '?id=' + id, { withCredentials: true })
  }
  public updateCustomer(id: number,customer: Customer): Observable<Customer> {
    return this.http.put<Customer>('http://localhost:8080/CouponSystemWeb/rest/admin/UpdtCustomer', customer, { withCredentials: true })
  }
  public getAllCustomer(): Observable<Customer[]> {
    return this.http.get<Customer[]>(this.customerUrl, { withCredentials: true })
  }
}

несколько моментов: я не использую SQL для своей базы данных.Я не использую: InMemoryDataService.

ОБНОВЛЕНИЕ: он не работает с Почтальоном.

Код сервера:

@Path("company")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CompanyService {

    @Context
    private HttpServletRequest requst;

    @POST
    @Path(" couponCrt")
    public Response createCoupon(Coupon coupon) {
        HttpSession session = requst.getSession(false);
        CompanyFacade companyFacade = (CompanyFacade) session.getAttribute("companyFacade");
        try {
            companyFacade.createCoupon(coupon);
            return Response.status(Status.CREATED).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new CouponSystemWebExeption("Error while creating Coupon : " + coupon.getTitle());
        }
    }

1 Ответ

0 голосов
/ 01 апреля 2019

Для ваших сообщений или запросов на размещение вы должны сначала преобразовать его в строку json, как показано ниже

public createCustomer(customer: Customer): Observable<Customer> {
let body = JSON.stringify(customer);
    return this.http.post<Customer>(this.customerCrtUrl, body, { withCredentials: true })
  }

, и для ошибки 404 вы можете открыть любой URL-адрес get в браузере, чтобы проверить, работает ли он нормально или нет?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...