简体   繁体   English

CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。 在 reactjs 中使用 iframe 时

[英]CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. while using iframe in reactjs

I'm looking to access a site from a button using iframe .我正在寻找使用iframe从按钮访问网站 This site authorizes access to all domain names.本网站授权访问所有域名。 Here is the code for my button:这是我的按钮的代码:

<Button
        component={NavLink}
        activeClassName={classes.activeBtn}
        to="/searchEngine"
        className={classes.buttonItemMiddle}
      >
        {location.pathname == '/searchEngine' ? (
          <Home fontSize="large" style={{ color: 'rgb(0,133,243)' }} />
        ) : (
          <HomeOutlined fontSize="large" />
        )}
      </Button> 

Here is my code in App.js :这是我在App.js中的代码:

<Route path='/searchEngine' component={() => { 
                          <iframe src="https://gkwhelps.herokuapp.com" title="Search engine"></iframe>
                          return null;
                          }}/>

But when I run my app and click the button, it returns nothing and I get the following error when inspecting my code on the browser:但是当我运行我的应用程序并单击按钮时,它什么也不返回,并且在浏览器上检查我的代码时出现以下错误:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=O7fVlw-' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I reloaded the solution from the Internet and specifically from this question on stack overflow and from this blog and added the following code in my App.js file:我从互联网上重新加载了解决方案,特别是从这个关于堆栈溢出的问题和这个博客中,并在我的App.js文件中添加了以下代码:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "https://gkwhelps.herokuapp.com"),
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"),
  next(),
})

but that did not solve the problem.但这并没有解决问题。 here is the content of my backend index.js file:这是我的后端index.js文件的内容:

const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
require("dotenv").config()
const app = express()
const http = require('http')
const server = http.createServer(app)
const io = require('socket.io')(server)

const UserRoutes = require('./routes/User')
const AuthRoutes = require('./routes/Auth')
const PostRoutes = require('./routes/Post')

const PORT = process.env.PORT || 5000
const {MONGODB_URI} = require("./config")

app.use(cors())
app.use(express.json())

app.use((req, res, next) => {
  
  io.req = req
  req.io = io
  next()
})

app.use('/api/auth', AuthRoutes)
app.use('/api/user', UserRoutes)
app.use('/api/post', PostRoutes)

require('./socket')(io)

mongoose
  .connect(MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() => {
    console.log('database connected')
    server.listen(PORT, () => console.log(`server started on port ${PORT}`))
  })
  .catch((err) => console.log(err))

To solve this problem,I also search the solution in the documentation and in this blog I modified my index.js file as follows:为了解决这个问题,我也在文档中搜索了解决方案,在这个博客中我修改了我的index.js文件如下:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'localhost:3000')
  io.req = req
  req.io = io
  next()
})

but without success.但没有成功。 My frontend package.json file is here:我的前端package.json文件在这里:

{
  "name": "firebase",
  "version": "0.1.0",
  "private": true,
  
  "dependencies": {
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@fortawesome/fontawesome-svg-core": "^6.1.1",
    "@fortawesome/free-brands-svg-icons": "^6.1.1",
    "@fortawesome/free-regular-svg-icons": "^6.1.1",
    "@fortawesome/free-solid-svg-icons": "^6.1.1",
    "@fortawesome/react-fontawesome": "^0.1.18",
    "@material-ui/core": "^4.12.4",
    "@material-ui/icons": "^4.11.3",
    "@material-ui/lab": "^4.0.0-alpha.61",
    "@mui/material": "^5.8.1",
    "@react-google-maps/api": "^2.11.8",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "0.27.2",
    "classnames": "2.2.6",
    "dotenv": "8.2.0",
    "emoji-picker-react": "^3.5.1",
    
    "install": "^0.13.0",
    "jwt-decode": "3.1.2",
    "moment": "^2.29.3",
    "node-fetch": "^3.2.4",
    "npm": "^8.11.0",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-eva-icons": "0.0.8",
    "react-hook-google-maps": "^0.0.3",
    "react-moment": "^1.1.2",
    "react-router-dom": "5.3.3",
    "react-scripts": "5.0.1",
    "socket.io-client": "4.5.1",
    "words-to-numbers": "1.5.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "web-vitals": "^2.1.4"
  }
}

my backend package.json file:我的后端package.json文件:

{
  "name": "backend",
  "version": "1.0.0",
  "license": "MIT",
  "main": "index.js",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"npm start\" \"npm run client\"",
    "start": "node backend/index.js",
    "server": "nodemon backend/index.js",
    "client": "npm start --prefix frontend"
  },
  "dependencies": {
    "bcrypt": "^5.0.0",
    
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.7.3",
    "mongoose": "^5.10.7",
    "multer": "^1.4.2",
    "socket.io": "^4.4.1"
  },
  "devDependencies": {
    "concurrently": "^7.2.2",
    "nodemon": "^2.0.4"
  }
}

I think this is happening because your frontend is trying to send requests to an endpoint running on the same domain(localhost).我认为这是因为您的前端正在尝试将请求发送到在同一域(本地主机)上运行的端点。 But this your error is not thrown by express.但是这个你的错误不是由快递抛出的。 That's why the solution you try to apply didn't work.这就是为什么您尝试应用的解决方案不起作用的原因。

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS) event when you are working on localhost.从 Socket.IO v3 开始,您需要在 localhost 上工作时显式启用跨域资源共享 (CORS) 事件。

intead const io = require('socket.io')(server) in your code you can do that : intead const io = require('socket.io')(server)在您的代码中,您可以这样做:

const { Server }= require('socket.io');
const io = new Server(httpServer, {
  cors: {
    origin: "http://localhost:3000"
  }
});

You can read the official doc handling cors `您可以阅读官方文档处理 cors `

Hey, there are several ways to solve the CORS errors.嘿,有几种方法可以解决 CORS 错误。 Here i'm attaching some of resources that was useful solving all sorts of CORS errors i faced.在这里,我附上了一些有用的资源,这些资源有助于解决我面临的各种 CORS 错误。

Solving CORS from client side if you dont have access to server 如果您无权访问服务器,则从客户端解决 CORS

All types of CORS Error and there Solution所有类型的 CORS 错误及其解决方案

Bonus:奖金:

you can have your own proxy URl by deploying this project onto heroku您可以通过将此项目部署到 heroku 上来拥有自己的代理 URl

  • You can even for testing purpose use Chrome Extension of CORS.您甚至可以出于测试目的使用 CORS 的 Chrome 扩展。

Would happy to help if you couldn't find the way from all the above resources.如果您无法从上述所有资源中找到方法,我们很乐意提供帮助。 Thanks!谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 政策阻止了获取“url”的访问:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS - Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 如何修复“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 - How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' 被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 Java 带有 CrossOrigin("*") 注释的后端 - Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Java Backend with CrossOrigin("*") annotation CORS问题-“所请求的资源上没有&#39;Access-Control-Allow-Origin&#39;标头。” - CORS-issue - “No 'Access-Control-Allow-Origin' header is present on the requested resource.” 请求的资源上不存在 Access-Control-Allow-Origin header。 将请求的模式设置为 no-cors 以获取禁用 CORS 的资源 - No Access-Control-Allow-Origin header is present on the requested resource. set the request's mode to no-cors to fetch the resource with CORS disabled 请求的资源上不存在“Access-Control-Allow-Origin”标头。 使用 Javascript 运行 Python 脚本时 - No 'Access-Control-Allow-Origin' header is present on the requested resource. when running a Python script using Javascript 将 fetch 与 Passport 结合使用会得到“请求的资源上不存在‘Access-Control-Allow-Origin’标头。” - Using fetch with Passport gets "No 'Access-Control-Allow-Origin' header is present on the requested resource." CORS 策略阻止了对获取的访问:请求的资源上不存在“Access-Control-Allow-Origin”header - Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource localhost:4200 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM