簡體   English   中英

由於 CORS 無法向 springboot 應用程序發出請求

[英]Cannot make request to springboot app because of CORS

我嘗試向托管在 heroku 上的 springboot 應用程序發出 POST 請求,

const email = 'x@x.com';
const password = 'x';

const data = JSON.stringify({
    email,
    password
});

fetch(
    'https://culinareat-test.herokuapp.com/api/user/users/_login', 
    {
        method: 'POST',
        headers : {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        },
        body : data,
    }
).then(res => {
    console.log(res);
})

我得到這個作為回應:
回復

這是我的 springboot 應用程序上的 controller:

@RestController
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    @RequestMapping(method = RequestMethod.POST, value = "/user/users/_login")
    public LoginResponse logUserIn(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request){
        return userService.logUserIn(loginRequest, response, request);
    }

    //another endpoints
}

我試圖從我剛剛在stackoverflow上閱讀的另一篇文章中做到這一點:

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
    }
}

盡管如此,它什么也沒做,我仍然不能做這個請求。 有什么建議我該怎么辦? 我應該在服務器端添加什么嗎? 提前致謝!

您需要在 controller 中添加注釋 @CrossOrigin

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    @RequestMapping(method = RequestMethod.POST, value = "/user/users/_login")
    public LoginResponse logUserIn(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request){
        return userService.logUserIn(loginRequest, response, request);
    }

    //another endpoints
}

請記住,瀏覽器會引發跨域問題。 默認情況下,如果您在源http://localhost上運行 javascript,則不能在后端為localhost指定 CORS。

Chrome等瀏覽器不允許javascript運行在origin http://localhost上跨域共享資源。 請參閱答案https://stackoverflow.com/a/10892392/15262845

解決方案很簡單。 hosts文件中將域,例如example.com解析為127.0.0.1 然后請求example.com:8080example.com以加載您的前端應用程序並發布來自example.com來源的請求。


此外,您始終可以通過導航到Network選項卡並復制、粘貼以下兩個標題來調試 CORS。

access-control-allow-credentials: true
access-control-allow-origin: http://example.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM