我正在尝试使用 axios 从 Reactjs 向 ASP.NET API 发送 post 请求。起初,我收到 400 Bad request 错误。但是在我更改后端的 DTO 后,它起作用了,但是接收到的数据为空或为空(我认为这是模型绑定错误之一)。 这是我的 React.Js 文件:
const defaultImgPath = '/assets/ImgStarter.jpg';
const initialFieldValues = {
productName: 'Fried spring rolls',
productPrice: 50000,
productStatus: 1,
productDescription: 'A short description',
imagePath: defaultImgPath,
imgName: '',
ProductImg: null
}
const ApiUploadImg = () => {
const [input, setInput] = useState(initialFieldValues)
const handleAddProduct = (e) => {
e.preventDefault();
axios.post('http://localhost:5273/api/product', input)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
})
return (
<div className='form-uload'>
<form className='p-5' onSubmit={handleAddProduct}>
<Input
inputType="text"
labelname="Product name"
name="productName"
setInput={setInput}
input={input}
/>
<Input
inputType="number"
labelname="Price"
name="productPrice"
setInput={setInput}
input={input}
/>
<Input
inputType="text"
labelname="Status (Is available?)"
name="productStatus"
setInput={setInput}
input={input}
/>
<Input
inputType="text"
labelname="Description"
name="productDescription"
setInput={setInput}
input={input}
/>
<Input
inputType="file"
labelname="Image"
name="productImg"
setInput={setInput}
input={input}
onChange={handlePreviewImg}
/>
<div>
<img
src={input.imagePath}
className='preview-img'
/>
</div>
<button type='submit' className='form-controls btn btn-primary'>Submit</button>
</form>
</div>
)
}
我的Input.js组件:
const Input = ({ setInput, input, labelname, name, inputType, onChange=null}) => {
const [value, setValue] = useState('');
const onChangeHanlder = (e) => {
setInput({...input, [name]: e.target.value})
}
var id = {name};
return (
<Fragment>
<label htmlFor={id} className='font-semibold text-white'>
{labelname}:
</label>
<input
id={id}
type={inputType}
name={name}
className='rounded input_form form-control mt-2 w-100'
// placeholder={placeholder}
onChange={onChange ? onChange : onChangeHanlder}
/>
</Fragment>
)
}
我的api函数:
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateProductRequestDTO requestDTO)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var productModel = requestDTO.ToProductsFromCreateDTO();
await _productRepo.CreateAsync(productModel);
return CreatedAtAction(nameof(GetById), new {id = productModel.Id}, productModel.ToProductDTO());
}
还有主角,我上面提到的DTO。我真的认为这将是最后一个可能发生错误的地方,因为我从上面提到的 ReactJs 文件中复制粘贴了“name”属性并创建了这个 DTO(解决方案(1))。但这没有用。因此,我粘贴了 Products 类中的属性,但正如我所说,此方法使接收到的数据为空(解决方案(2))
public class CreateProductRequestDTO
{
//Solution (1)
// public string? ProductName {get; set; } = string.Empty;
// public int ProductPrice {get; set; }
// public bool ProductStatus {get; set; }
// public string? ProductDescription {get; set; } = string.Empty;
//Solution (2)
public string Name {get; set; } = string.Empty;
public int Price {get; set; }
public bool Status {get; set; }
public string Description {get; set; } = string.Empty;
}
如果您需要它,“输入”对象看起来与“initialFieldValues”完全相同 有人可以向我解释一下发生了什么事吗?
尝试使用 FromForm。
[HttpPost]
public async Task<IActionResult> Create([FromForm] CreateProductRequestDTO requestDTO)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var productModel = requestDTO.ToProductsFromCreateDTO();
await _productRepo.CreateAsync(productModel);
return CreatedAtAction(nameof(GetById), new {id = productModel.Id}, productModel.ToProductDTO());
}
如果这没有帮助,请尝试给出解析调用的示例。