当我试图从我的react应用程序中获取API时,当我的笔记本电脑通过LAN连接时,它会显示以下错误消息。

但是,当我的笔记本电脑通过移动热点连接时,它不会显示任何错误。当我在localhost:5000中运行我的API时,它在终端上显示了这个错误消息。
Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/我已经访问了我的IP地址,当我通过移动热点连接时,它工作得很好。
为什么会发生这种情况,以及如何修复它?
我可以获取其他API,但不能获取我的API。接口链接:https://invoicesapi.herokuapp.com/api/invoices Github回购:https://github.com/rishipurwar1/invoice_api
app.js接口代码:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const connectDB = require('./config/db');
// routes
const invoices = require('./routes/api/invoices');
// Init Middleware
app.use(express.json({ extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', "*");
res.setHeader('Access-Control-Allow-Methods', "POST,GET,OPTIONS");
res.setHeader('Access-Control-Allow-Headers', "Content-Type, Authorization");
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Connect Database
connectDB();
app.get('/api', (req, res) => {
res.render('index')
});
app.use('/api', invoices);
app.listen(port, () => {
console.log('Server is started');
})发布于 2021-09-21 14:57:33
您应该考虑使用cors包(https://www.npmjs.com/package/cors)
npm install cors将此文件添加到app.js文件:
var cors = require('cors')
var corsOptions = {
origin: 'http://yoursite.com',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))https://stackoverflow.com/questions/69266515
复制相似问题