The*_*ory 7 localhost node.js cors express ngrok
我知道这种问题以前已经解决过,但我无法确切地弄清楚为什么它不适合我的情况。
我正在本地开发一个网站,我想在各种平台和设备上测试它,所以我决定使用 ngrok 来实现这一点。
我的前端在端口 3000 上运行,我的 Express 服务器在端口 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).
在我的 Express 服务器上,我确保使用 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();
});
Run Code Online (Sandbox Code Playgroud)
来源:为什么将 CORS 标头添加到 OPTIONS 路由不允许浏览器访问我的 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
Run Code Online (Sandbox Code Playgroud)
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
});
Run Code Online (Sandbox Code Playgroud)
由于本地主机的性质,这是否可以工作?
Firefox 和 Chrome 都有同样的问题。
谢谢您的帮助!
步骤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());
Run Code Online (Sandbox Code Playgroud)
第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
Run Code Online (Sandbox Code Playgroud)
步骤3:
最后,我打开 ngrok 并输入:
ngrok http 5000
Run Code Online (Sandbox Code Playgroud)
现在应该可以了。
| 归档时间: |
|
| 查看次数: |
23579 次 |
| 最近记录: |