[英]Why does my fetch method not return JSON?
I have an ASP.NET Core project with React as the framework.我有一个以 React 作为框架的 ASP.NET Core 项目。
I use the following model:我使用以下模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace drivingSchoolManagement.Models
{
[Serializable]
public class Customers
{
public int Id { get; set; }
public string First_name { get; set; }
public string Last_name { get; set; }
public string Address { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public bool Is_active { get; set; }
}
}
And the following Controller:以及以下控制器:
using drivingSchoolManagement.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace drivingSchoolManagement.Controllers
{
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class CustomersController : ControllerBase
{
private readonly ILogger<CustomersController> _logger;
private readonly DatabaseConnection _dbConnection;
public CustomersController(ILogger<CustomersController> logger, DatabaseConnection dbConnection)
{
_logger = logger;
_dbConnection = dbConnection;
}
[HttpGet]
public JsonResult Get()
{
return new JsonResult(_dbConnection.GetAllCustomers());
}
}
}
In my React component Customers.js I want to output the data I get, for this I wrote the following:在我的 React 组件 Customers.js 中,我想输出我得到的数据,为此我写了以下内容:
import React, { Component } from 'react';
export class Customers extends Component {
static displayName = Customers.name;
constructor(props) {
super(props);
this.state = { customers: [] };
this.getCustomers();
}
async getCustomers() {
try {
const response = await fetch('customers', {
headers: {
Accept: 'application/json',
},
});
console.log(response);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
this.setState({ customers: data });
} catch (error) {
console.log(error);
}
}
render() {
const customers = this.state.customers.map(customer => {
return (
<div key={customer.id}>
<p>ID: {customer.id}</p>
<p>First name: {customer.first_name}</p>
<p>Last name: {customer.last_name}</p>
<p>Address: {customer.address}</p>
<p>Zip: {customer.zip}</p>
<p>Phone: {customer.phone}</p>
<p>Email: {customer.email}</p>
<p>Is active: {customer.is_active ? 'Yes' : 'No'}</p>
</div>
);
});
return (
<div>
<h1>Customers</h1>
{customers}
</div>
);
}
}
Also in my DatabaseConnection.cs I have folling:同样在我的 DatabaseConnection.cs 中,我有以下内容:
public List<Customers> GetAllCustomers()
{
List<Customers> customers = new List<Customers>();
using (NpgsqlConnection connection = OpenConnection())
{
string query = "SELECT * FROM customers";
NpgsqlCommand command = new NpgsqlCommand(query, connection);
using (NpgsqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
customers.Add(new Customers
{
Id = reader.GetInt32(0),
First_name = reader.GetString(1),
Last_name = reader.GetString(2),
Address = reader.GetString(3),
Zip = reader.GetString(4),
Phone = reader.GetString(5),
Email = reader.GetString(6),
Is_active = reader.GetBoolean(7)
});
}
}
}
return customers;
}
The Status is 404 not found, also the type is html.状态是 404 未找到,类型也是 html。 Maybe you overlook what I did wrong.
也许你忽略了我做错了什么。
I think the problem is the fetch('customers')
part.我认为问题出在
fetch('customers')
部分。
It should be fetch('/customers')
(starting with a slash).它应该是
fetch('/customers')
(以斜杠开头)。
I don't know why fetch behaves like this (so, differently with/without slash), but let me explain the 'problem'.我不知道为什么fetch的行为是这样的(所以,有/没有斜线不同),但让我解释一下“问题”。
The anatomy of a URL is like this: URL 的结构是这样的:
Focus on the domain and path , forget the others for now.专注于domain和path ,暂时忘记其他的。
fetch('/customers')
When you use a URL starting with a slash /
, it replaces the entire path part from the URL.当您使用以斜杠
/
开头的 URL 时,它会替换 URL 中的整个路径部分。
So: www.example.com/path/to/myfile -> www.example.com/customers所以: www.example.com/path/to/myfile -> www.example.com/customers
fetch('customers')
When you use a URL that doesn't start with a slash /
, it somehow replaces only the last part of the path (in case it contains multiple parts).当您使用不以斜杠
/
开头的 URL 时,它会以某种方式仅替换路径的最后一部分(如果它包含多个部分)。
So: www.example.com/path/to/myfile -> www.example.com/path/to/customers所以: www.example.com/path/to/myfile -> www.example.com/path/to/customers
You wouldn't notice this kind of behaviour in case the path contained only 1 part, as the resulting URL would be the same in both cases (either with or without /
).如果路径仅包含一个部分,您不会注意到这种行为,因为在这两种情况下生成的 URL 都是相同的(有或没有
/
)。
Hope it helps.希望能帮助到你。
Have you tried using the forward slash like this?您是否尝试过像这样使用正斜杠?
const response = await fetch('/customers', {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.