为什么通过ngrok进行隧道传输时会出现CORS错误?

时间:2020-03-04 19:57:46

标签: node.js express cors localhost ngrok

我知道这种问题以前已经解决过,但是我无法弄清楚为什么它不适用于我的情况。

我正在本地网站上工作,我想在各种平台和设备上对其进行测试,所以我决定为此使用ngrok。

我的前端在端口3000上运行,而我的快速服务器在端口5000上运行。

所以我打开ngrok并输入ngrok http 3000

在运行服务器的本地PC上,https://example.ngrok.io正常运行,没有任何问题。

但是在我的笔记本电脑(或其他设备)上,前端正确显示,但是当实际上要从后端获取数据时,它显示错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/weather/51.87575912475586,0.9436600208282471. (Reason: CORS request did not succeed).

在我的快递服务器上,我确保使用cors软件包和app.use(cors());,并且还尝试手动添加标头:

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

来源:Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

这也是我的代码,在这里我提取和获取数据以防万一我在那做错了事:

index.js(前端)

const response = await fetch(`http://localhost:5000/weather/${lat},${lng}`); //sending request to server-side

const json = await response.json();

console.log(json); //getting the weather data from server-side

server.js(后端)

const express = require("express");
const mongoose = require("mongoose");
const fetch = require("node-fetch");
const cors = require('cors');
const nodemailer = require('nodemailer');
require('dotenv').config();

const users = require('./routes/api/users');

const app = express();


//Json Middleware
app.use(express.json());

app.use(cors());


//Getting URI from keys file
const db = require('./config/keys').mongoURI;


//Connect to the Database
mongoose.set('useUnifiedTopology', true);
mongoose.set('useCreateIndex', true);
mongoose.connect(db, {useNewUrlParser: true})
.then(()=> console.log("Database Connected"))
.catch(err=> console.log(err));

//Route for user routes
app.use('/api/users',users);

const dbport = process.env.PORT || 5000;

app.listen(dbport, () => console.log(`Server started on port ${dbport}`));

app.get('/weather/:latlon', async (req,res) =>{ //awating request from client-side

    const latlon = req.params.latlon.split(',');

    console.log(req.params);

    const lat = latlon[0];
    const lon = latlon[1];

    console.log(lat,lon);

    const api_key = process.env.API_KEY;

    const weather_url = `https://api.darksky.net/forecast/${api_key}/${lat},${lon}?units=auto`; //getting data from weather API
    const fetch_res = await fetch(weather_url);
    const json = await fetch_res.json();
    res.json(json); //sending weather data back to client-side
});

由于本地主机的性质,这种方法是否可行?

firefox和chrome都有相同的问题。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

经过几天的抓挠,我终于找到了解决方案,下面将其发布给其他可能遇到相同问题的解决方案。

第1步:

我没有启用2个端口(客户端为3000,服务器为5000),而是关闭了客户端端口,并使用express直接从服务器上提供了客户端文件夹/资产:

const dbport = process.env.PORT || 5000;

app.listen(dbport, () => console.log(`Server started on port ${dbport}`));

app.use(express.static('client')); //serving client side from express
//Json Middleware
app.use(express.json());

第2步:

现在,我们为客户端和服务器都提供了一个端口(端口5000),我进入了客户端,在那里我执行了获取请求(请参见上面的index.js),并将实际请求修改为相对:

const response = await fetch(`/weather/${lat},${lng}`); //sending request to server-side


const json = await response.json();

console.log(json); //getting the weather data from server-side 

第3步:

最后,我打开ngrok并输入:

ngrok http 5000

它现在应该可以工作了。

答案 1 :(得分:0)

如果您将 ngrok 与 nodejs/express.js 一起使用。

删除他的cors导入并使用此代码:

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match 
the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content- 
Type, Accept");
next();
});

将“YOUR-DOMAIN.TLD”替换为“*”以访问所有网址或您的特定网站网址。

详情请参阅https://enable-cors.org/server_expressjs.html

谢谢。