微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从UI应用程序到Servant服务器进行调用时发生CORS问题 服务器部分 UI部分问题描述:问题

如何解决从UI应用程序到Servant服务器进行调用时发生CORS问题 服务器部分 UI部分问题描述:问题

我发现了许多与CORS相关的问题,但没有一个解决了我的问题。由于我对Web开发非常陌生,因此非常感谢我在建立和运行项目基础架构方面的帮助。

我的应用程序由两部分组成:

服务器部分

  • 由Servant Haskell制造的服务器。我一直尝试连接的最重要的端点是:
type Unprotected =
    "login" 
        :> ReqBody '[JSON] Credentials 
        :> Verb 'POST 204 '[JSON] (Headers '[Header "Set-Cookie" SetCookie,Header "Set-Cookie" SetCookie] NoContent)

它基于此处描述的项目:https://github.com/haskell-servant/servant-auth

我已经找到了一个有关CORS的问题:CORS header ‘Access-Control-Allow-Origin’ missing in servant,但这没有帮助。

在开发过程中,我在端口8081上启动服务器。

UI部分

  • 我还有一个UI项目,该项目独立托管在端口8833上。它使用WebPack。我还发现了一些有关CORS的SO帖子,建议使用:
  devServer: {
    headers: {
      "Access-Control-Allow-Origin": "*","Access-Control-Allow-Credentials": "true","Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,PATCH,OPTIONS","Access-Control-Allow-Headers": "X-Requested-With,content-type,Authorization"
    }

那也没有帮助。

问题描述:

当我在UI项目中进行“提取调用时,尝试与Servant端点通信:

Access to fetch at 'http://localhost:8081/login' from origin 'http://localhost:8833' 
has been blocked by CORS policy: Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an 
opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource 
with CORS disabled.

我使用提取的方式:

        let data = {
            credentialsUserName: this.state.login,credentialsPassword: this.state.password
        };

        let opts : Requestinit = { 
            method: "POST",headers: new Headers({ "Content-Type": "application/json" }),body: JSON.stringify(data)
        };

        fetch("http://localhost:8081/login",opts).then((value) => {
            console.log(value);
            // do something later
        });

问题

我应该怎么做才能使提取与服务方端点正常工作。另外,我的应用程序体系结构有什么问题吗?也许有更好的设计方法

最后一件事:我的应用程序的整个代码很长,所以我决定只在这里放置最重要的部分。如果需要,可以随时要求更多。

编辑1

发送获取请求后,我可以在浏览器的“网络”标签中看到两个条目。

一个带有以下标题

content-type: application/json
Referer: http://localhost:8833/Login
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/85.0.4183.83 Safari/537.36
我在其主体中包含的

和json数据。状态为“(失败)net :: ERR_Failed”。

一个的状态为400,并且包含更多标题

Accept: */*
Accept-Encoding: gzip,deflate,br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:8833
Referer: http://localhost:8833/Login
Sec-Fetch-Dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/85.0.4183.83 Safari/537.36

有趣的是,在“常规”标签中,我可以看到:

Request URL: http://localhost:8081/login
Request Method: OPTIONS
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:8081
Referrer Policy: no-referrer-when-downgrade

请求方法“ OPTIONS”看起来很神秘。为什么在那儿?

作为一个快速的猜测,我尝试在Haskell的CORS定义中添加“ OPTIONS”,但这次也没有运气:

port :: Int
port = 8081

corsPolicy :: Middleware
corsPolicy = cors (const $ Just policy)
    where
      policy = simpleCorsResourcePolicy
        { corsMethods = [ "GET","POST","PUT","OPTIONS" ]}

main :: IO ()
main = do
    migrateDB
    jwtConfig <- getJwtConfig
    putStrLn $ "Serving endpoint " ++ (show port)
    run port $ corsPolicy $ serveWithContext proxy (context cookieConfig jwtConfig) (appAPI cookieConfig jwtConfig)
编辑2

感谢您的帮助-我已经成功配置了Servant,这里是:

corsPolicy :: Middleware
corsPolicy = cors (const $ Just policy)
    where
        policy = simpleCorsResourcePolicy
          { 
              corsMethods = [ "GET","OPTIONS" ],corsOrigins = Just (["http://localhost:8833"],True),corsRequestHeaders = [ "authorization","content-type" ]
          }

Main的其余部分与我之前的清单中一样。 认情况下,Haskell CORS不接受任何标头。我打算发送的甚至不是“ Content-Type”。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。