我正在使用http-proxy-middleware
(并愿意接受建议,但想坚持使用代理请求的模块,而不是创建诸如request
或http
之类的新请求)向远程主机的请求。
我看不到当前的两个问题:
1)我有一个受CSRF保护的表格(通过csurf
)。我希望中间件首先检查CSRF令牌,如果只有它才有效,然后将请求代理到另一个主机,获取响应并将其发送给用户。如何实现这样的设置?
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)
答案 0 :(得分:0)
在您的代码void*
中,保护工作在代理中间件之后。如果您只想保护这两条路线csrf
:
'/api/one','/api/two'
或者,如果您想保护对API的所有app.use(['/api/one','/api/two'], csrfProtection, proxy('http://example.com'))
app.use('/api', proxy('http://example.com'))
请求,则需要这样做:
POST