【问题标题】:@CrossOrigin Annotation works on one method of the Rest Controller , but doesn't apply for the second one [closed]@CrossOrigin Annotation 适用于 Rest Controller 的一种方法,但不适用于第二种方法[关闭]
【发布时间】:2021-05-18 18:53:03
【问题描述】:

简短说明。我正在尝试在后端设置一些休息端点,并从前端调用它们。

我有两种相同的方法(除了路径不同),一种没有问题,但是较新的方法在部署后被任何浏览器上的 CORS 策略阻止( AppEngine )。当然,我在本地进行了测试,但使用的是 Postman,我们都知道它不受 CORS 政策的限制。

我将代码留在下面,但我无法理解其中一个是如何工作的,而另一个则被阻止了。

包 com.sjww.SecurityJobsWorldWide.controller;

import com.mashape.unirest.http.exceptions.UnirestException;
import com.sjww.SecurityJobsWorldWide.model.ContactModel;
import com.sjww.SecurityJobsWorldWide.model.NewsletterModel;
import com.sjww.SecurityJobsWorldWide.service.EmailService;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class EmailController {

    private final EmailService emailService;

    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @PostMapping(value = "/sendContactMail", consumes = "application/json")
    public String sendMail(@RequestBody ContactModel contactModel) throws UnirestException {
        emailService.sendContactMessage(contactModel);
        return new JSONObject()
                .put("message", "SUCCESS!")
                .toString();
    }

    @PostMapping(value = "/addOnRegistration", consumes = "application/json")
    public String addToNewsletterList(@RequestBody NewsletterModel newsletterModel) throws UnirestException {
        emailService.addListMember(newsletterModel.getEmail());
        return new JSONObject()
                .put("message", "Added to newsletter!")
                .toString();
    }
}

我试图在每个方法上移动 CrossOrigin 注释,没有。我试图准确地指定哪个起源但同样的故事适用。一个有效,另一个无效。

所以 sendEmail() 是旧的。而 addToNewsletterList 是新的,因为 CORS 而无法使用。

“No 'Access-Control-Allow-Origin' header is present on the requested resource”错误

我不得不提一下,我没有尝试设置某种规则的 WebMvc 配置类。它只是这个控制器,还有更多具有相同注释 @CrossOrigin 但只是这种方法不起作用。

提前谢谢你。

【问题讨论】:

  • 嗨,OP,您是否尝试在@RestController 上方设置@CrossOrigin?请参阅baeldung.com/spring-cors。让我知道这是否有效
  • 你好,我实际上试过你的版本,同样的故事。可悲的是不起作用。我也尝试了@Boug 提到的,但这也不起作用。

标签: java google-app-engine spring-security cors


【解决方案1】:

我发现了“错误”。

问题是我正在执行 http post 请求,如下所示:

this.httpClient.post<any>("SERVER_URL", "{email: " + result.user.email + "}").subscribe

意思是我忘了从前端添加这部分:

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

并将其作为参数添加如下

this.httpClient.post<any>("SERVER_URL", "{email: " + result.user.email + "}", httpOptions).subscribe

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 2021-11-04
    • 2013-04-20
    • 2017-10-19
    • 2013-01-28
    • 1970-01-01
    • 2012-09-13
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多