I'm looking to access a site from a button using 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
:
<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.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:
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:
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:
{
"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:
{
"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.
intead const io = require('socket.io')(server)
in your code you can do that :
const { Server }= require('socket.io');
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000"
}
});
You can read the official doc handling cors `
Hey, there are several ways to solve the CORS errors. Here i'm attaching some of resources that was useful solving all sorts of CORS errors i faced.
Solving CORS from client side if you dont have access to server
Bonus:
you can have your own proxy URl by deploying this project onto heroku
Would happy to help if you couldn't find the way from all the above resources. Thanks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.