CORS 策略已阻止从源“localhost:3000"访问“..."处的 XMLHttpRequest [英] Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy

查看:27
本文介绍了CORS 策略已阻止从源“localhost:3000"访问“..."处的 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是重复的,但我还没有找到专门与我的问题相关的主题.

This may be a duplicate, but I havent found a thread relating specifically to my issue.

我正在进行以下 API 调用:

I am making the following API call:

const config = {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
  }
};

const {
  data: { ip }
} = await axios.get("https://api.ipify.org?format=json", config);

这会引发错误:

从源 'http://localhost:3000' 访问 XMLHttpRequest at 'https://api.ipify.org/?format=json' 已被 CORS 策略阻止:对预检请求的响应没有't 通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.

当我将我的应用程序部署到 Heroku 时,API 调用按预期工作.但是在我的本地机器上开发时它不起作用.不确定我在这里遗漏了什么.

When I deploy my app to Heroku, the API call works as expected. However it does not work when developing on my local machine. Not sure what I'm missing here.

推荐答案

如果你正在 nodejs 中构建你的 rest api.按照以下简单步骤

if you are building your rest api in nodejs. Follow the folowing simple steps

停止 Node.js 服务器.

Stop the Node.js server.

npm install cors --save

将以下行添加到您的 server.js 或 index.js

Add following lines to your server.js or index.js

var cors = require('cors')

app.use(cors()) // Use this after the variable declaration

现在尝试在客户端进行 api 调用,它应该可以工作

Now try to make your api call on the client side and it should work

这篇关于CORS 策略已阻止从源“localhost:3000"访问“..."处的 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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