我是 Node.Js 的新手,我写了两种方法 post 和 get。首先,我希望帖子看起来像 get 请求(异步函数),以便我可以从不同的 js 文件中导出它,但我不确定它现在是否是异步的。其次,我希望 get 请求也能够发送带有 url 的 cookie。
这是场景:1-发送发布请求并设置cookie。服务器会将我定向到另一个位置。2-获取位置并发送获取请求并包含cookie。
这是我的 POST 代码:
request.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: 'http://example/login',
body: 'mes=heydude',
followRedirect: true,
form: {
username: 'usr',
password: 'pass'
}
}, function (error, response, body) {
if (error) {
console.log(error)
}
var setCookie = response.headers['set-cookie']
console.log('login success')
console.log(body)
})
这种方法工作正常,但如何使其成为异步函数?像下面的获取请求?还有如何让get请求返回cookie和html?
function fetch (url, callback) {
return new Promise(function (resolve, reject) {
request(url, function (error, response, html) {
if (error) {
return reject(error)
}
if (response.statusCode !== 200) {
return reject(new Error('error code'))
}
return resolve(html)
})
})
}
如果有一个模块可以在 NPM 上做到这一点,请告诉我谢谢。帮助新手并获得奖杯!
如果您使用 Express,您应该查看cookie-parser。这是一个处理 cookie(顾名思义)的库,因此您不必重新发明轮子。
如果你不知道Express是什么,我建议你看一下。
Express 是一个最小且灵活的 Node.js Web 应用程序框架,它为 Web 和移动应用程序提供了一组强大的功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句