Browse Source

创建专门的位置更新API端点,解决位置信息无法写入数据库的问题

pull/1/head
SwTt29 2 months ago
parent
commit
95a88200d3
  1. 18
      pages/profile/index.js
  2. 44
      server-example/server-mysql.js

18
pages/profile/index.js

@ -779,7 +779,7 @@ Page({
// 构造上传的数据,包含authorized_region字段和必要的phoneNumber
let userInfo = {
authorized_region: JSON.stringify(locationData) // 直接在前端转换为JSON字符串,确保数据格式正确
authorized_region: locationData // 直接传递对象,由API层处理序列化
};
// 确保包含phoneNumber字段(服务器接口要求)
@ -827,10 +827,18 @@ Page({
// 调用API上传位置数据
const api = require('../../utils/api.js');
api.uploadUserInfo({
...userInfo,
openid: openid // 明确传递openid
}).then(res => {
// 使用专门的位置更新API端点
const locationUpdateData = {
openid: openid,
latitude: latitude,
longitude: longitude
};
console.log('调用位置更新API:', locationUpdateData);
api.request('/api/user/update-location', 'POST', locationUpdateData)
.then(res => {
console.log('位置数据上传成功:', res);
// 显示上传成功提示
wx.showToast({

44
server-example/server-mysql.js

@ -1185,6 +1185,50 @@ async function createUserAssociations(user) {
// API路由
// 专门用于更新用户位置信息的API端点
app.post('/api/user/update-location', async (req, res) => {
try {
const { openid, latitude, longitude } = req.body;
if (!openid) {
return res.json({ success: false, message: '缺少openid' });
}
if (!latitude || !longitude) {
return res.json({ success: false, message: '缺少位置信息' });
}
const locationData = { latitude, longitude };
const locationJson = JSON.stringify(locationData);
console.log('更新用户位置信息:', { openid, locationJson });
const updateResult = await User.update(
{ authorized_region: locationJson, updated_at: getBeijingTime() },
{ where: { openid } }
);
console.log('位置更新结果:', updateResult);
if (updateResult[0] > 0) {
// 查询更新后的用户数据
const updatedUser = await User.findOne({ where: { openid }, attributes: ['authorized_region'] });
console.log('更新后的位置信息:', updatedUser.authorized_region);
return res.json({
success: true,
message: '位置信息更新成功',
data: { authorized_region: updatedUser.authorized_region }
});
} else {
return res.json({ success: false, message: '用户不存在或位置信息未更新' });
}
} catch (error) {
console.error('更新位置信息失败:', error);
res.json({ success: false, message: '更新位置信息失败', error: error.message });
}
});
// 上传用户信息
app.post('/api/user/upload', async (req, res) => {
try {

Loading…
Cancel
Save