未通过外部API处理CORS预检请求

未通过外部API处理CORS预检请求

本文介绍了未通过外部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.

在网络"标签中,我有:

And in the network tab I have:

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

据我所知,使用API​​不能正确处理来自网络浏览器的复杂"请求.

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预检请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:58