我想知道当某些 JSON 数据从服务器发送到客户端时存储在不同目录中的位置。
我正在尝试构建简单的 API,将 JSON 数据从服务器端(端口号:5001)发送到客户端(端口号:3000)。
我在做这个项目时注意到,http header 和 body 不是要包含 JSON 的地方。
如果是这样,JSON 数据如何传送到客户端? 我想知道代码隐藏中发生了什么。
以下是我编写的用于构建简单 API 的代码:
客户端代码:
componentDidMount() {
axios.get('localhost:5001')
.then((result) => console.log(result))
.catch((err) => console.log('Error ocurred'));
}
服务器端代码(ASP.NET Core 2.0):
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json;
charset=utf-8";
await context.Response.WriteAsync(json);
我预计名为“result”的 JSON 数据将附加到 HTTP header 或正文,但事实并非如此。当我在控制台查看http body的原始数据时,只是html内容。这是浏览器上显示的内容:
{"id":1,"Name":"jay","Password":"1004","Content":"这是来自服务器的文本"
正如我在代码中所写,我希望控制台而不是浏览器 View 页面上显示此数据。
最佳答案
看来您从服务器端返回了错误。你应该首先Enable Cross-Origin Requests (CORS) in ASP.NET Core
在 ConfigureServices
中将 CORS 添加到您的 web api:
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
并在 Configure
函数中启用它:
app.UseCors("MyPolicy");
如果你有中间件来修改你的 web api 中的响应:
app.Run(async (context) =>
{
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json; charset = utf - 8";
await context.Response.WriteAsync(json);
});
在客户端中,您可以通过访问 .data
作为响应来获取结果:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function test(){
axios.get('http://localhost:5001/api/values')
.then(
(result) => console.log(result.data)
)
.catch(
(err) => console.log('Error ocurred')
);
}
</script>
关于json - 当我通过 AJAX 获取 JSON 数据时,数据存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284499/