【发布时间】:2017-10-01 03:34:37
【问题描述】:
我写了一个查询,它给我一个表中的帖子,还返回一个关于每个帖子作者的信息:
SELECT post.id, post.text, post.datetime, JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as author
FROM post
INNER JOIN user ON post.authorId = user.id;
但作为响应,author 字段是一个字符串:
author: "{"username": "@", "firstName": null}"
datetime: "2017-05-02T20:23:23.000Z"
id: 10
text: "5555"
我尝试使用CAST 来解决这个问题,但无论如何author 是一个字符串:
CAST(JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as JSON) as author
为什么会发生这种情况以及如何解决?
更新:
我使用 Node.js 和 Express 从服务器发送数据:
app.get('/posts', (req, res, next) => {
getPosts().then((posts) => {
res.setHeader('Content-Type', 'application/json');
res.send(posts);
})
.catch(next);
});
// ...
getPosts() {
return new Promise((resolve, reject) => {
const query = `
SELECT post.id, post.text, post.datetime, JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as author
FROM post
INNER JOIN user ON post.authorId = user.id;`;
this.connection.query(query, (err, result) => {
if(err) {
return reject(new Error("An error occured getting the posts: " + err));
}
console.log(result) // prints author as a string
resolve(result || []);
});
});
}
console.log 的结果:
{
id: 1,
text: 'hello, world!',
datetime: 2017-05-02T15:08:34.000Z,
author: '{"username": "@", "firstName": null}'
}
我也尝试在这里将res.send(posts) 更改为res.json(posts),但这并没有帮助。
来自客户端的我的功能是接触服务器以获取帖子:
export const getPosts = () => {
customFetch(apiUrl + '/posts')
.then(response => response.json())
.then(json => json)
};
【问题讨论】:
-
可能特定于您使用的编程语言。顺便说一句,它是什么?
-
我使用 javascript
-
我不是节点专家,但我的理解是它有多种不同的方式连接到 RDBMS,遗憾的是您选择的似乎不支持 json 对象。 JSON 毕竟是最近添加到 mysql 的一些东西
-
我同意@e4c5,这可能是由于客户端如何处理MySQL返回的json对象。您可能必须在 js 代码中将字符串显式转换为 json。
-
@Shadow 我已经这样做了。我更新了我的帖子并从客户端添加了一个触摸服务器的功能。
标签: javascript mysql json node.js express