外部 API 未处理 CORS 预检请求 [英] CORS preflight request not handled by external API

查看:30
本文介绍了外部 API 未处理 CORS 预检请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 getresponse.com 创建前端应用程序.它有自己的 API,位于 https://api.getresponse.com.当我尝试使用 Axios 或 Fetch 执行任何 javascript 请求表单浏览器时,出现此错误:

I'm trying to create front-end application for getresponse.com. It has own API which located at https://api.getresponse.com. When I'm trying to do any javascript request form browser with Axios or Fetch I've got this error:

Access to XMLHttpRequest at 'https://api.getresponse.com/v3/accounts' from origin 'http://localhost:8080' 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.

在网络标签中,我有:

Request URL: https://api.getresponse.com/v3/accounts
Request Method: OPTIONS
Status Code: 400 Bad Request

因此,据我所知,API 无法正确处理来自 Web 浏览器的复杂"请求.

So, as far as I can understand with API can't work with 'complex' requests from web browser properly.

现在我只有一个想法 - 制作一些中间件,它将我的请求代理到 API 端点,而无需任何飞行前请求.

Now I've got only one idea - to make some middleware, which will proxy my requests to API endpoints without any pre-flight requests.

我说得对吗?我找不到任何此类中间件的示例.我在哪里可以找到任何信息?

Am I right? I can't find any examples of such a middleware. Where can I find any information?

推荐答案

James 的回答没问题,但现在我更喜欢基于 Node.js 而不是 Nginx 的解决方案,因为我在 Windows 上进行本地开发.我想出了 Express 服务器的解决方案:

James answer is ok, but right now I'm more comfortable with solution based on Node.js rather than Nginx, as I developing locally on windows. I came up to the solutions with Express server:

var cors = require('cors')
var app = express()
var proxy = require('express-http-proxy'); 

app.use(cors())

app.use('/', proxy('https://api.getresponse.com'))

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

这篇关于外部 API 未处理 CORS 预检请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆