如何在DigitalOcean中限制对Express API的访问 [英] How to limit access to Express API in DigitalOcean
问题描述
我在DigitalOceans上有2个应用程序,一个Express,API和一个React应用程序. React应用程序从API获取数据.我想确保除了我的React应用程序之外没有人可以访问此API.我正在使用Ubuntu 18.04.
I have 2 applications on DigitalOceans, an Express, API, and a React application. React application gets data from API. I want to make sure no one can access this API other than my React application. I'm using Ubuntu 18.04.
- 我的React应用程序位于 www.example.com
- 我的API在 api.example.com 上
- My React application is on www.example.com
- My API is on api.example.com
推荐答案
您可以使用 Express中的CORS 是一种机制,它允许从域外的另一个域请求网页上的受限资源.
You could use CORS in Express which is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain.
注意:由于您的应用不需要登录,因此我建议您这样做.
NOTE: I'm recommending this one given your app does not require login.
首先,在您的后端中安装该库:
First, install the library in your backend:
npm install cors
第二,设置允许的来源:
Second, setup the allowed origin:
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
您可以在 CORS中间件
这篇关于如何在DigitalOcean中限制对Express API的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!