小宝管理系统爬坑记录

1.前后端分离的跨域cookie的问题

我后端使用的node+express
最开始使用中间件设置下允许跨域
这下子前端可以通过ajax请求到后端的数据了

1
2
3
4
5
6
7
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});

我以为这样就够了
后来发现前端无法携带后端set的cookie
此处一脸懵逼,一度怀疑我设置cookie的方法写错了,用cookies模块不行,用express自己的cookie也不行。
后来发现 原来是cookie无法跨域。
需要再添加一条 Access-Control-Allow-Credentials:true
表示允许跨域携带cookie,
并且要将Access-Control-Allow-Origin指定到具体的域,否则cookie不会带到客户端。
感觉这样设置麻烦。。。。。
于是在npm发现了一个专门跨域的包 cors

1
2
const cors = require('cors')
app.use(cors({credentials: true, origin: 'http://localhost:8080'}));

由于前端我用axios发送的ajax请求,所以还要设置下axios
withCredentials: true
允许携带凭证
这样就ok拉~

###2.async函数中foreach中嵌套异步操作(同步函数中使用foreach而且foreach中还包含异步请求,foreach不会等待异步执行完,才结束循环,而是直接循环玩调到foreach的下一段代码片段)

看不懂没关系,我只是做个记录,怕自己忘了,有时间写详细的!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function sendWeatherInfo({time="0 * * * * *",Contact}) {
console.log('天气服务开启成功');
console.log('天气推送时间间隔'+time);
schedule.scheduleJob(time, async () => {
//获取相关信息,citys用户有哪些城市['Beijing','Dalian']
let citys = await getCity();
let weatherUsers = [];
//获取天气数据
await(() => {
return new Promise((resolve, reject) => {
let n = 0;
citys.forEach(async item => {
let { data } = await $http.get(baseURL + item);
if(data) n++;
weatherUsers.push({ city: item, user: [] ,data});
if(n==citys.length){
resolve('数据请求成功')
}
});
})
})()

//将用户以不同的地区分类
await getUsersClassify(weatherUsers);
// console.log(weatherUsers);

//处理天气
let baseText = ``;
weatherUsers.forEach((item) => {
//处理数据
let weCity = item.data.results[0].location.name;
let weData = item.data.results[0].daily[0];
// console.log(weData);
//解构数据
let {date,text_day,text_night,high,low,wind_direction,wind_direction_degree,wind_speed,wind_scale} = weData;
//获取eomoj
let {getEmoj} = require('./getEmoj'); //TODO:完善emoji内容
let dayEmoj = getEmoj(text_day);
let nightEmoj = getEmoj(text_night);
let normalText = `${weCity}今日白天/:sun${text_day}${dayEmoj}\n今日夜间/:moon${text_night}${nightEmoj}\n最高气温${high}°C,最低气温${low}°C\n${wind_direction}风,💨指数${wind_scale}`;
item.user.forEach(async (user) => {
let a = await Contact.find({
alias:user
})
if(a.star()){ //是否为星标用户,名字高亮
await a.say(`亲爱哒/:rose✨${a.name()}✨\n${normalText}`)
console.log(`向【VIP】用户昵称${a.name()},ID:${a.alias()}推送天气成功`);
}else{
//普通用户,无名字
await a.say(normalText);
console.log(`向【普通】用户昵称${a.name()},ID:${a.alias()}推送天气成功`);
}
})
})
});
}
0%