我正在使用http-proxy-middleware (并接受建议,但我想坚持使用代理请求的模块,而不是创建新的模块,如request或http)来代理远程主机的请求。
我没有看到当前解决方案的两个问题:
1)我有一个受CSRF保护的表单(通过csurf)。我希望中间件首先检查CSRF-token,如果它是有效的,则将请求代理到另一个主机,获得响应并将其发送给用户。如何实现这样的设置?
2) http-proxy-middleware (和其他一些代理模块)利用app.use来设置一个转发规则(将路由附加到主机),但是我希望对路由进行更细粒度的控制-我的每个路由必须在远程主机上有自己的端点。
代码:
const express = require('express')
const csrf = require('csurf')
const cookieParser = require('cookie-parser')
const proxy = require('http-proxy-middleware')
var app = express()
var csrfProtection = csrf({ cookie: true })
app.use(cookieParser())
// not quite what I need, since different
// routes would utilize different endpoints
app.use('/api', proxy('http://example.com'))
app.get('/forms', (req, res) => {
res.send(
res.render('csrf-protected-forms.html', { csrfToken: req.csrfToken() })
)
})
app.post('/api/one', csrfProtection, (req, res) => {
response = // proxies to 'http://example.com/something/one'
// and obtains response
res.send(response)
})
app.post('/api/two', csrfProtection, (req, res) => {
response = // proxies to 'http://example.com/somethingelse/and/here/two'
// and obtains response
res.send(response)
})
app.listen(3000)发布于 2019-09-18 07:07:47
在您的代码中,csrf保护在代理中间件之后运行。如果您只想保护这两条路由,请使用'/api/one','/api/two'
app.use(['/api/one','/api/two'], csrfProtection, proxy('http://example.com'))
app.use('/api', proxy('http://example.com'))或者,如果你想保护对API的所有POST请求,你需要做一些事情:
app.use('/api', csrfProtection, proxy('http://example.com'))https://stackoverflow.com/questions/57982926
复制相似问题