- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从我正在执行的 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/
我是一名优秀的程序员,十分优秀!