CORS Origin FAILED Spring BootJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 CORS Origin FAILED Spring Boot

Сообщение Anonymous »

Вы нужны мне, потому что @CROSSOrigin не работает, и я не понимаю почему, у вас здесь мой код. На самом деле, я использую WebService, но у меня проблема с «Acess-Control-Allow-Origin». Я попробовал все, но ничего не помогло, пожалуйста, помогите мне! class="snippet">

Код: Выделить всё

zone.js:3243 GET http://localhost:8080/apiEquipment/equipments 404
localhost/:1 Access to XMLHttpRequest at 'http://localhost:8080/apiEquipment/equipments' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone.js:3243 XHR failed loading: GET "http://localhost:8080/apiEquipment/equipments".
core.js:15714 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/apiEquipment/equipments", ok: false, …}


pom.xml

Код: Выделить всё


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.2.RELEASE
  

com.example
GoSecuriServices
0.0.1-SNAPSHOT
GoSecuriServices
Rest API for GoSecuri Application


1.8




org.springframework.boot
spring-boot-starter-data-jpa


org.springframework.boot
spring-boot-starter-data-rest


org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-web-services



org.springframework.boot
spring-boot-devtools
runtime


mysql
mysql-connector-java
runtime


org.springframework.boot
spring-boot-starter-test
test






org.springframework.boot
spring-boot-maven-plugin






Application.java

Код: Выделить всё

package com.example.GoSecuriServices;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories("com.example.GoSecuriServices.repository")
@EntityScan("com.example.GoSecuriServices.model")
@ComponentScan
@SpringBootApplication
public class GoSecuriServicesApplication {

public static void main(String[] args) {
SpringApplication.run(GoSecuriServicesApplication.class, args);
}

}


Equipment.java (моя таблица)

Код: Выделить всё

package model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;

@Entity
@Table(name = "Equipment")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},  allowGetters = true)
public class Equipment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Equipment_id;

@NotBlank
private String EquipmentName;

@NotBlank
private Integer Nb;

// Getters and Setters
public Long getEquipment_id() {
return this.Equipment_id;
}

public void SetEquipment_id(Long id) {
this.Equipment_id = id;
}

public String getEquipmentName() {
return this.EquipmentName;
}

public void setEquipmentName(String name) {
this.EquipmentName = name;
}

public Integer getNb() {
return this.Nb;
}

public void setNb(Integer nb) {
this.Nb = nb;
}

}


EquipmentRepository.java

Код: Выделить всё

package repository;

import model.Equipment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EquipmentRepository extends JpaRepository {

}


EquipmentController.java

Код: Выделить всё

package controller;

import exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Equipment;
import repository.EquipmentRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
@RequestMapping("/apiEquipment")
public class EquipmentController {

@Autowired
EquipmentRepository equipmentRepository;

@RequestMapping(value= "/apiEquipment/**", method=RequestMethod.OPTIONS)
public void corsHeaders(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
response.addHeader("Access-Control-Max-Age", "3600");
}

// Get all equipments
@GetMapping("/equipments")
public List getAllEquipments() {
return equipmentRepository.findAll();
}

// Create new equipment
@PostMapping("/equipments")
public Equipment createEquipment(@Valid @RequestBody Equipment equipment) {
return equipmentRepository.save(equipment);
}

// Get a single equipment
@GetMapping("/equipments/{id}")
public Equipment getEquipmentById(@PathVariable(value = "id") Long equipmentId) {
return equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
}

// Update a Equipment
@PutMapping("/equipments/{id}")
public Equipment updateNote(@PathVariable(value = "id") Long equipmentId,
@Valid @RequestBody Equipment equipmentDetails) {

Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));

equipment.setEquipmentName(equipmentDetails.getEquipmentName());
equipment.setNb(equipmentDetails.getNb());

Equipment updatedEquipment = equipmentRepository.save(equipment);
return updatedEquipment;
}

// Delete a Equipment
@DeleteMapping("/equipments/{id}")
public ResponseEntity deleteEquipment(@PathVariable(value = "id") Long equipmentId) {
Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));

equipmentRepository.delete(equipment);

return ResponseEntity.ok().build();
}

}



Подробнее здесь: https://stackoverflow.com/questions/544 ... pring-boot
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»