shiro解决cors_使用Netlify Dev彻底解决CORS

shiro解决cors

访问控制允许标题和CORS (Access-Control-Allow-Headers and CORS)

Say you’re a budding young (or young-at-heart!) frontend developer. You’d really love to smush together a bunch of third party APIs for your next Hackathon project. This API looks great: https://icanhazdadjoke.com/api! We’ll build the next great Dad Joke app in the world! Excitedly, you whip up a small app (these examples use React, but the principles are framework agnostic):

假设您是一个崭露头角的年轻(或年轻的!)前端开发人员。 您真的很想为您的下一个Hackathon项目融合大量第三方API。 这个API看起来很棒: https : //icanhazdadjoke.com/api ! 我们将构建世界上下一个伟大的爸爸笑话应用程序! 令人兴奋的是,您启动了一个小应用程序(这些示例使用React,但是原理与框架无关):

function App() {
  const [msg, setMsg] = React.useState("click the button")
  const handler = () =>
    fetch("https://icanhazdadjoke.com/", { headers: { accept: "Accept: application/json" } })
      .then((x) => x.json())
      .then(({ msg }) => setMsg(msg))

  return (
    <div className="App">
      <header className="App-header">
        <p>message: {msg}</p>
        <button onClick={handler}> click meeee</button>
      </header>
    </div>
  )
}

You excitedly yarn start to test your new app locally, and…

您很兴奋地yarn start在本地测试您的新应用,然后…

Access to fetch at 'https://icanhazdadjoke.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field accept is not allowed by Access-Control-Allow-Headers in preflight response.

Oh no, you think, I’ve seen this before but how do I fix this again?

哦,不 ,您认为, 我以前已经看过这个,但是我该如何解决呢?

You google around and find this browser plugin and this serverside fix and this way too long MDN article and its all much too much for just a simple API request. First of all, you don’t have control of the API, so adding a CORS header is out of the question. Second of all, this problem is happening because you’re hitting an https:// API from http://localhost, which doesn’t have SSL, so the problem could go away once you deploy onto an https enabled domain, but that still doesn’t solve the local development experience. Last of all, you just wanted to get something up and running and now you’re stuck Googling icky security stuff on step 1.

您在Google周围搜索,发现此浏览器插件此服务器端修复程序,以及这样的MDN文章太长,对于一个简单的API请求而言,它的内容太多了。 首先,您没有对该API的控制权,因此添加CORS标头是不可能的。 第二,发生此问题是因为您正在从http://localhost一个https:// API,该API没有SSL,因此,一旦部署到启用了https域,该问题就可能消失了,但是仍然不能解决本地开发经验。 最后,您只想启动并运行某些东西,现在您在第一步中陷入了谷歌搜索棘手的安全问题。

Super frustrating. Now that more and more of the web is HTTPS by default, you’re just going to run into this more and more as you work on clientside apps (one reason server-side frameworks actually don’t even face CORS problems because they are run in trusted environments).

超级令人沮丧。 现在, 默认情况下越来越多的Web是HTTPS,在处理客户端应用程序时,您将越来越多地使用它(原因之一是服务器端框架实际上因为运行而不会遇到CORS问题)在受信任的环境中)。

Netlify Dev,本地代理解决方案 (Netlify Dev, the Local Proxy Solution)

If you’ve looked around long enough you’ll notice that CORS is a browser protection that completely doesn’t apply if you just made the request from a server you control. In other words, spin up a proxy server and all your problems go away. The only problem has been spinning up this proxy has been too hard and too costly. And that’s just for local dev; the deployed experience is totally different and just adds more complexity to the setup.

如果您已经看了足够长的时间,就会发现CORS是一种浏览器保护功能,如果您只是从所控制的服务器发出请求,则该保护功能将完全不适用。 换句话说,启动代理服务器,您所有的问题都会消失。 唯一的问题是分解代理程序太难了,也太昂贵了。 那只是为了本地开发者。 部署的体验完全不同,只会增加设置的复杂性。

For the past few months I’ve been working on Netlify Dev, which aims to be a great proxy server for exactly this kind of usecase. It comes embedded in the Netlify CLI, which you can download:

在过去的几个月中,我一直在从事Netlify Dev的工作, Netlify Dev的目标是成为一种很好的代理服务器,以解决此类用例。 它内置在Netlify CLI中,您可以下载:

$ npm i -g netlify-cli

Now in your project, if it is a popular project we support like create-react-app, Next.js, Gatsby, Vue-CLI, Nuxt and so on, you should be able to run:

现在在您的项目中,如果它是我们支持的热门项目,例如create-react-app,Next.js,Gatsby,Vue-CLI,Nuxt等 ,您应该可以运行:

# provide a build command and publish folder
# specific to your project,
# create a Netlify site instance, and
# initialize netlify.toml config file if repo connected to git remote
$ netlify init # or `ntl init`

# start local proxy server
$ netlify dev # or `ntl dev`

And you should see the proxy server run on localhost:8888 if that port is available.

如果该端口可用,您应该会看到代理服务器在localhost:8888上运行。

If your project isn’t supported, you can write and contribute your own config, but it should be a zero config experience for the vast majority of people.

如果不支持您的项目,则可以编写和贡献自己的config ,但是对于大多数人来说,它应该是零配置的体验。

As of right now it is a local proxy server that just blindly proxies your project, nothing too impressive. Time to spin up a serverless function!

到目前为止,它是一个本地代理服务器,仅盲目地代理您的项目,没有什么令人印象深刻的。 是时候启动无服务器功能了!

创建一个Netlify函数 (Creating a Netlify Function)

At this point you should have a netlify.toml file with a functions field. You can handwrite your own if you wish, but it should look like this:

此时,您应该具有一个带有functions字段的netlify.toml文件。 您可以根据需要手写您自己的手写内容,但它应如下所示:

[build]
  command = "yarn run build"
  functions = "functions"
  publish = "dist"

You can configure each one of these to your needs, just check the Netlify docs. But in any case, now when you run:

您可以根据需要配置其中的每一个,只需查看Netlify docs即可 。 但是无论如何,现在运行时:

$ netlify functions:create

the CLI shows you the list of function templates. Pick node-fetch and it will scaffold a new serverless function for you in /functions/node-fetch by default, including installing any required dependencies. Have a look at the generated files, but the most important one will be functions/node-fetch/node-fetch.js. By convention the folder name must match the file name for the function entry point to be recognized.

CLI将显示功能模板列表。 选择node-fetch ,默认情况下它将在/functions/node-fetch为您提供一个新的无服务器功能,包括安装所有必需的依赖项。 看一下生成的文件,但是最重要的是functions/node-fetch/node-fetch.js 。 按照约定,文件夹名称必须与要识别的功能入口点的文件名称匹配。

Great, so we now have a serverless Node.js function making our call to the API. The only remaining thing to do is to modify our frontend to ping our function proxy instead of directly hitting the API:

太好了,因此我们现在有了一个无服务器的Node.js函数,可以调用该API。 剩下要做的唯一事情是修改我们的前端以ping我们的功能代理,而不是直接访问API:

const handler = () =>
  fetch("/.netlify/functions/node-fetch", { headers: { accept: "Accept: application/json" } })
    .then((x) => x.json())
    .then(({ msg }) => setMsg(msg))

在本地开发中摆脱CORS (Getting rid of CORS in local development)

Now when we run the proxy server again:

现在,当我们再次运行代理服务器时:

$ netlify dev # or ntl dev

And head to the proxy port (usually http://localhost:8888), and click the button…

并转到代理端口(通常为http://localhost:8888 ),然后单击按钮……

message: Why can't a bicycle stand on its own? It's two-tired.

Funny! and we can laugh now that we have got rid of our CORS issues.

滑稽! 现在我们已经摆脱了CORS问题,现在我们可以笑了。

在生产中部署和消除CORS (Deploying and Getting rid of CORS in production)

When deploying, we lose the local proxy, but gain the warm embrace of the production environment, which, by design, is going to work the exact same way.

部署时,我们失去了本地代理,但获得了生产环境的热烈拥护, 根据设计 ,生产环境将以完全相同的方式工作。

$ npm run build ## in case you need it
$ netlify deploy --prod ## this is the manual deploy process

And head to the deployed site (run netlify open:site).

并转到已部署的站点(运行netlify open:site )。

Note: if you are deploying your site via continuous deployment from GitHub, GitLab or BitBucket, you will want to modify your netlify.toml build command to install function dependencies:

注意:如果要通过从GitHub,GitLab或BitBucket进行连续部署来部署站点,则需要修改netlify.toml build命令以安装功能依赖项:

[build]
  command = "yarn build && cd functions/node-fetch && yarn"
  functions = "functions"
  publish = "dist"

Now you know how to spin up a function to proxy literally any API, together with using confidential API keys (either hardcoded, although don’t do this if your project is Open Source, or as environment variables) that you don’t want to expose to your end user, in minutes. This helps to mitigate any production CORS issues as well, although those are more rare.

现在,您知道了如何启动一个函数以代理所有的API,以及使用机密的API密钥(可以是硬编码的,尽管如果您的项目是开源的,则不要这样做,或者作为环境变量 ),在几分钟之内向最终用户展示。 这也有助于缓解生产中的CORS问题,尽管这种情况更为罕见。

If you have simple endpoints and files to proxy, you may also choose to use Netlify Redirect Rewrites to accomplish what we just did in one line, however it is of course less customizable.

如果您有简单的终结点和要代理的文件,则还可以选择使用Netlify重定向重写来完成我们刚刚完成的工作,但是当然它的可定制性较低。

That’s all there is to solving your CORS problems once and for all! Note that Netlify Dev is still in beta, if you ran into any hiccups or have questions, please file an issue!

一劳永逸地解决您的CORS问题! 请注意,Netlify Dev仍处于测试阶段,如果您遇到任何麻烦或有疑问, 请提出问题

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-solve-cors-once-and-for-all-netlify-dev

shiro解决cors

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值