gpt4 book ai didi

javascript - 如何从 API 调用中获取响应 JSON

转载 作者:行者123 更新时间:2023-12-02 23:54:25 26 4
gpt4 key购买 nike

我想从我正在执行的 api 调用中检索 JSON 响应。例如,我想检索如下内容:

{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year": 2019,"月":"三月","日":31,"playmorning":0,"playafternoon":1,"playevening":1}}

这是我在 React 中使用 fetch 的 API 调用。 (是的,我知道在 URL 中发送密码是不好的,这是为了学校项目)

        fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})

这是我正在调用的 API 调用。

app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;

var user = req.params.user;
var password = req.query.password;

console.log(user, password);

var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});

当我在 fetch 调用中执行 console.log(res) 时,打印的内容如下:

响应 {type: "basic", url: "http://localhost:3000/api/user/tim?password=123 ", 重定向: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: headers {}ok: trueredirected : falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123 "proto: Response

当我访问网站时,输出是:

{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year": 2019,"月":"三月","日":31,"playmorning":0,"playafternoon":1,"playevening":1}}

这就是我想要的。

最佳答案

一般来说,这就是从 Promise 返回响应正文的方式。

fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then‌​(data=> {
console.log(data);
})

关于javascript - 如何从 API 调用中获取响应 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com