Reputation: 47
I want to know the place where certain JSON data get stored when it's sent from server to client which exists in the different directory.
I am trying to build simple API which send JSON data from server side(port number:5001) to client side(port number:3000).
What I noticed doing this project is that http header and body is not the place where the JSON to be contained.
If so, how does JSON data get delivered to client side? I want to know what happen in code-behind.
Following is the code that I wrote to build simple API:
Client side code:
componentDidMount() {
axios.get('localhost:5001')
.then((result) => console.log(result))
.catch((err) => console.log('Error ocurred'));
}
Server side code(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);
I expected that the JSON data named 'result' will be attached to HTTP header or body but it was not. When I checked the raw data of http body on the console, it was just html content. This is the content displayed on the browser:
{"id":1,"Name":"jay","Password":"1004","Content":"This is text from the server"}
as I wrote in the code, I want this data on the console not on the browser view page.
Upvotes: 1
Views: 63
Reputation: 27568
That seems you get error returned form server side . You should firstly Enable Cross-Origin Requests (CORS) in ASP.NET Core
Add CORS to your web api in ConfigureServices
:
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And enable that in Configure
function :
app.UseCors("MyPolicy");
If you have middleware to modify the response in your 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);
});
In client , you could get the result by accessing .data
in response :
<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>
Upvotes: 1