我正在尝试运行springboot并设置restconroller以将json返回到我的angular项目中。我在类级别添加了@crossorigin(origins=“”,allowedheaders=“”),但我的网站仍然返回以下错误。
从本质上说,我正在尝试让一个运行在s3 bucket中的angular应用程序连接到运行在kubernetes pod中的spring boot应用程序,以运行kafa生产者和消费者的东西。当我在本地运行kafka、spring和angular时(在不同的端口上),它都可以工作,但是当我尝试在s3和容器中运行时,它失败了,出现下面的corrs错误。因为这是一个学校的项目,我不关心如何获得正确的corrs安全的细节,我只想让它允许一切,这样我就可以证明我的kafa的东西在spring端工作时,我通过我的应用程序提交数据。
corrs错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<IPADDR>:8080/survey-submit. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<IPADDR>:8080/survey-submit. (Reason: CORS request did not succeed).
ERROR
{…}
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for http://<IPADDR>:8080/survey-submit: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://<IPADDR>:8080/survey-submit"
Angular 测量表代码
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
@Component({
selector: 'app-survey',
templateUrl: './survey.component.html',
styleUrls: ['./survey.component.css']
})
export class SurveyComponent implements OnInit {
private surveyForm: FormGroup;
private likeBest: Array<String> = ['Students', 'Location', 'Campus', 'Atmosphere', 'Dorms', 'Sports'];
private selectedBest = [];
private response: string;
constructor(private http: HttpClient, private _fb: FormBuilder, private router: Router) {
this.surveyForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
addrStreet: new FormControl(),
addrCity: new FormControl(),
addrState: new FormControl(),
addrZip: new FormControl(),
phone: new FormControl(),
email: new FormControl(),
date: new FormControl(),
likeBest: this.addLikeBest(),
howHeard: new FormControl(),
recommendLikelihood: new FormControl()
});
}
addLikeBest() {
const arr = this.likeBest.map(e => {
return this._fb.control(false)
})
return this._fb.array(arr);
}
get likeBestAry() {
return <FormArray>this.surveyForm.get('likeBest')
}
getSelectedBestValues() {
this.selectedBest = [];
this.likeBestAry.controls.forEach((control, i) => {
if (control.value) {
this.selectedBest.push(this.likeBest[i])
}
})
}
ngOnInit(): void {
}
private postData() {
console.log(this.selectedBest)
const inputData = {
nameFirst: this.surveyForm.value.firstName,
nameLast: this.surveyForm.value.lastName,
addrStreet: this.surveyForm.value.addrStreet,
addrCity: this.surveyForm.value.addrCity,
addrState: this.surveyForm.value.addrState,
addrZip: this.surveyForm.value.addrZip,
phone: this.surveyForm.value.phone,
email: this.surveyForm.value.email,
date: this.surveyForm.value.date,
likeBest: this.selectedBest.join(),
howHeard: this.surveyForm.value.howHeard,
recommendLikelihood: this.surveyForm.value.recommendLikelihood
}
this.http.post<any>('http://<IPFORSPRINGBOOTCONTAINER>:8080/survey-submit', inputData).subscribe({
next: data => {
console.log("test " + data);
this.response = 'Item Saved.';
}
})
}
}
Spring BootKafka配置
import edu.swe645.walton.hw1.model.Survey;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.support.serializer.JsonSerializer;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KakfaConfiguration {
Logger logger = LoggerFactory.getLogger("KakfaConfiguration.class");
@Bean
public ProducerFactory<String, Survey> producerFactory() {
Map<String, Object> config = new HashMap<>();
try {
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "<KAFKAIP>:31852");
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
} catch (Exception e){
logger.error("Error in class KakfaConfiguration, Method producerFactory, Message - " +e.getMessage());
}
return new DefaultKafkaProducerFactory<>(config);
}
@Bean
public KafkaTemplate<String, Survey> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
Map<String, Object> config = new HashMap<>();
try {
config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "<KAFKAIP>:31852");
config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id");
config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
}
catch (Exception e){
logger.error("Error in class KafkaConfiguration, Method consumerFactory, Message - " + e.getMessage());
}
return new DefaultKafkaConsumerFactory<>(config);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();
factory.setConsumerFactory(consumerFactory());
return factory;
}
}
Spring启动控制器
package edu.swe645.walton.hw1.resource;
import edu.swe645.walton.hw1.listner.KafkaConsumer;
import edu.swe645.walton.hw1.model.Survey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@Configuration
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class SurveyResource {
@Autowired
private KafkaTemplate<String, Survey> kafkaTemplate;
@Autowired
private KafkaConsumer myTopicConsumer;
Logger logger = LoggerFactory.getLogger("SurveyResource.class");
private static final String TOPIC = "survey-data-topic";
private int keyCounter = 0;
@PostMapping(path="/survey-submit")
public void postSurvey(@RequestBody Survey s)
{
try {
kafkaTemplate.send(TOPIC, "mykey" + ++keyCounter, s);
}
catch (Exception e){
logger.error("Error in class SurveyResource, Method postSurvey, Message - " + e.getMessage());
}
}
@GetMapping(path="/old-surveys", produces = "application/json")
public List<Survey> getMessages() {
return myTopicConsumer.getMessages();
}
}
编辑:我现在得到这个。。。。
我看到这个是镀铬的
1条答案
按热度按时间zysjyyx41#
您可以添加它作为一个过滤器,如下所示