基本上,我正在使用一家公司提供的一组给定 API 构建一个网站。从这里开始,我不允许访问或更改给定的 API。
API 的给出类似于下面的代码
http://domainname.com/data.aspx?action=login
使用该 API,我可以通过使用用户名和密码执行 POST 请求来成功返回 true 或 false。
接下来,我尝试获取具有相似给定 URL 的用户的详细信息
http://domainname.com/data.aspx?action=user_details
在上面的 API 中,它正在检查 Session["username"]。这就是我的问题出现的地方
从我这边来看,我正在使用nodejs。
var request = require('request');
var postData = {
'username': 'example',
'userpass': 'abc123',
};
request.get({url:'http://domainname.com/data.aspx?action=login', formData:postData}, function(err,httpResponse,body1){
console.log(body1);
request.get({url:'http://domainname.com/data.aspx?action=user_details'}, function(err,httpResponse,body2){
console.log(body2);
})
})
body1 的第一个 console.log 结果:true
body2 的第二个 console.log 结果:[](空数组)
为了确保 API 正常工作,我使用了 POSTMAN谷歌浏览器的扩展。首先,我登录用户,然后运行 user_details API,然后返回用户的详细信息。
我最后错过了什么?
最佳答案
默认情况下,Asp.net 保留名为 sessionId 的 cookie, 所以你必须通过“request”启用cookie。
Cookieless SessionIDs By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.
正如 Request 中所述文档, 默认情况下禁用 Cookie。
这是他们文档中的引用:
Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set jar to true (either in defaults or options).
var request = request.defaults({jar: true}) request('http://www.google.com', function () { request('http://images.google.com') })
启用 cookie 后,它会像 postman 和 chrome 一样工作。
关于javascript - 使用 NodeJS 以 C# 格式访问服务器的 API session 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617340/