【发布时间】:2018-08-11 15:03:00
【问题描述】:
我正在尝试使用 IHttpActionResult 将 JSON 结果返回给我的客户端。
我的 .Net 代码如下所示:
[AllowAnonymous, HttpPost, Route("")]
public IHttpActionResult Login(LoginRequest login)
{
if (login == null)
return BadRequest("No Data Provided");
var loginResponse = CheckUser(login.Username, login.Password);
if(loginResponse != null)
{
return Ok(new
{
message = "Login Success",
token = JwtManager.GenerateToken(login.Username, loginResponse.Roles),
success = true
});
}
return Ok( new
{
message = "Invalid Username/Password",
success = false
});
}
但这不起作用,因为在我的 JavaScript 提取之后,我似乎从未在响应中看到 JSON:
const fetchData = ( {method="GET", URL, data={}} ) => {
console.log("Calling FetchData with URL " + URL);
var header = {
'Content-Type': "application/json",
}
// If we have a bearer token, add it to the header.
if(typeof window.sessionStorage.accessToken != 'undefined')
{
header['Authorization'] = 'Bearer ' + window.sessionStorage.accessToken
}
var config = {
method: method,
headers: header
};
// I think this adds the data payload to the body, unless it's a get. Not sure what happens with a get.
if(method !== "GET") {
config = Object.assign({}, config, {body: JSON.stringify(data)});
}
// Use the browser api, fetch, to make the call.
return fetch(URL, config)
.then(response => {
console.log(response.body);
return response;
})
.catch(function (e) {
console.log("An error has occured while calling the API. " + e);
});
}
正文中没有可用的 JSON。 如何将结果返回给我的客户进行解析? response.body 没有 json 对象。
使用 striped 的建议:console.log(response.json())
我在那里看到了消息。它似乎在错误的地方。不应该在体内吗?
【问题讨论】:
-
你的console.log响应,它给出了什么?
-
你能调试吗?你能在浏览器开发工具中查看请求/响应吗?
-
@Crowcoder - 添加了屏幕截图。
-
@Striped - 添加了屏幕截图。
-
尝试
console.log(response.json())。
标签: javascript c# json