WeChat アプレットの開発プロセス中に、wx.request を使用してリクエストを行うと、リクエスト データがバックエンドに送信された後に Cookie が含まれないことがわかりましたが、その理由は、WeChat 開発ツールがリクエスト データを送信する必要があるためです。 wx.request は WeChat サーバーを介して行われるため、バックグラウンド サービスでは Cookie を取得できません。また、場合によっては、認証や検証に Cookie を使用することが避けられない場合があります。では、どうすればよいでしょうか?
実際には 2 つの解決策があります。
1. まず、wx.setStorage を通じて取得した Cookie をローカルに保存できます。
wx.request({
url: "https://请求路径",
method: "GET",
data: {
account: this.data.account,
password: this.data.password
},
success: (res) => {
//将请求的数据缓存起来
wx.setStorage({
key: 'cookie',
data: res.cookies,
success: function () {
console.log('缓存数据到本地');
}
});
}
})
その後、リクエストを呼び出すと、キャッシュされたばかりの Cookie データがヘッダーにスローされ、一緒にバックグラウンドに送信され、同時にバックグラウンドは Cookie を返してキャッシュを継続します。
wx.request({
url: "https://请求路径",
method: "GET",
header: {
'content-type': 'application/json',
'cookie': wx.getStorageSync('cookie').toString() // 设置cookie不使用tostring会出问题
},
data: {
account: this.data.account,
password: this.data.password
},
success: (res) => {
wx.setStorageSync("cookie", res.cookies)
console.log(res)
}
})
バックエンドコード:
@Autowired
StringRedisTemplate stringRedisTemplate;
@GetMapping("/admin/admingLogin")
public Admin login(String account, String password, HttpServletRequest req, HttpServletResponse resp){
String token= CookieUtil.getCookie("admin",req);
if (token!=null){
Admin admin= JSON.parseObject(stringRedisTemplate.opsForValue().get(token),Admin.class);
if(admin!=null)
CookieUtil.addCookie("admin", token, resp);
return admin;
}
String uuid = String.valueOf(UUID.randomUUID());
Admin admin = userMapper.login(account, password);
if(admin==null) return null;
String value = JSON.toJSONString(admin);
stringRedisTemplate.opsForValue().set(uuid, value);
CookieUtil.addCookie("admin", uuid, resp);
return admin;
}
public static void addCookie(String tokenName,String val,HttpServletResponse resp){
Cookie cookie=new Cookie(tokenName,val);
cookie.setMaxAge(3000);
cookie.setPath("/");
resp.addCookie(cookie);
}
2 番目の方法は、サードパーティのライブラリ weapp-cookie を使用することです。
npm install weapp-cookie --save
# 将 npm 包复制到 vendor 文件夹,避免小程序可能不能找到文件(tips:使用 wepy/mpvue 等框架无需此步)
cp -rf ./node_modules/ ./vendor/
// app.js
import './vendor/weapp-cookie/index'
// tips: 使用 wepy/mpvue 可以直接在入口 js 引入 weapp-cookie 模块
// import 'weapp-cookie'
App({
onLaunch: function () { }
// ...
})
起動中に未定義のエラーが報告される場合があります。weapp-cookie.es.js ではなく weapp-cookie.js が dist ファイルに存在することを確認してください。場所の特定が完了したら、wx.request を直接使用して Cookie リクエストを送信します。