Resolved Getting 404 from axios.post()

Dragon4ik

Member
Joined
Oct 24, 2020
Messages
16
Programming Experience
Beginner
Hello everybody!
I am a novice in ASP.NET and try to write my first application, whose client-size which is written in React.js, using this technology . This is the simple SPA, which should send the data from its form and getting respomse. But every request ends up with the message ("Uncaught (in promise) Error: Request failed with status code 404") and I can't resolve this problem.

Here is my FormComponent code:
C#:
import './Form.css'
import React, { Component } from 'react'
import axios from 'axios'

export default class Form extends Component {
  
    constructor(props){
        super(props)

        this.state={
            name: "",
            email: "",
            text: ""
        }

        this.onNameChange = this.onNameChange.bind(this);
        this.onEmailChange = this.onEmailChange.bind(this);
        this.onTextChange = this.onTextChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onNameChange(e) {
        this.setState({ name: e.target.value });
    }

    onEmailChange(e) {
        this.setState({ email: e.target.value });
    }

    onTextChange(e) {
        this.setState({ text: e.target.value });
    }

    onSubmit(e) {
        e.preventDefault();
        var commentName = this.state.name;
        var commentEmail = this.state.email;
        var commentText = this.state.text;
        if (!commentName || !commentEmail || !commentText) {
            return;
        }

        var data = new FormData(e.target);

        axios({
            method: 'post',
            url: '/',
            data: data,
        })
            .then((res) => {
                console.log(res);
            })
            .catch((err) => { throw err });

        this.setState({ name: "", email: "", text: "" });
      
    }

    render() {
        return (
            <section>
                <form id="my-form" onSubmit={this.onSubmit}>
                    <a id="feedback-btn" type="submit">Нам важлива ваша думка</a>
                    <label htmlFor="in_name">Ім'я:</label>
                    <input id="in_name" type="text" onChange={this.onNameChange}/>
                    <label htmlFor="in_email">Email:</label>
                    <input id="in_email" type="email" onChange={this.onEmailChange}></input>
                    <label htmlFor="text_feedback">Коментар:</label>
                    <textarea name="feedback" id="text_feedback" onChange={this.onTextChange}></textarea>
                    <button type="submit">Залиште відгук</button>
                </form>
            </section>
        )
    }
}
Controller API:
C#:
using Gazda.Models;
using Microsoft.AspNetCore.Mvc;
using System;

// For more information on enabling Web API for empty projects, visit [URL='https://go.microsoft.com/fwlink/?LinkID=397860']Part 3, add a view to an ASP.NET Core MVC app[/URL]

namespace Gazda.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class CommentController : ControllerBase
    {

        // POST api/<CommentController>
        [HttpPost]
        public IActionResult Post(Comment comment)
        {

            comment.Id = Guid.NewGuid().ToString();

            return Ok(comment);
        }

    }
}
And Comment Model:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Gazda.Models
{
    public class Comment
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Text { get; set; }
    }
}
I can't get, what I'm doing wrong. It seems to me it is very simple mistake, but I spendfor it a few hours and couldnt find any solution. Thanl you in advance!!!!
P.S. Sorry for my English
 
I fixed the post for readability by using code boxes like this:

insertcode.png
 
Set a breakpoint on your Controller's Post method. Is it even being reached?

Can PostMan or Swagger reach your Post method?
 
axios({ method: 'post', url: '/', data: data, })
The URL looks suspicious to me. Most ASP.NET WebAPI method URLs look something like "/api/<controller>/<method>/". So your URL should at least be "/api/Comment"
 
The URL looks suspicious to me. Most ASP.NET WebAPI method URLs look something like "/api/<controller>/<method>/". So your URL should at least be "/api/Comment"
Thank you so much. I changed URL and also passes information through dataForm.append(). Thanks to this I started to get a response from controller. But there the next problem appears: controller returns Comment object, which fields are null, except Id. What can be the reason of this problem?

Modified Form.js:
JavaScript:
import './Form.css'
import React, { Component } from 'react'
import axios from 'axios'

export default class Form extends Component {
    
    constructor(props){
        super(props)

        this.state={
            name: "",
            email: "",
            text: ""
        }

        this.onNameChange = this.onNameChange.bind(this);
        this.onEmailChange = this.onEmailChange.bind(this);
        this.onTextChange = this.onTextChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onNameChange(e) {
        this.setState({ name: e.target.value });
    }

    onEmailChange(e) {
        this.setState({ email: e.target.value });
    }

    onTextChange(e) {
        this.setState({ text: e.target.value });
    }

    onSubmit(e) {
        e.preventDefault();
        var commentName = this.state.name;
        var commentEmail = this.state.email;
        var commentText = this.state.text;
        if (!commentName || !commentEmail || !commentText) {
            return;
        }

        console.log(commentName);
        console.log(commentEmail);
        console.log(commentText);

        var data = new FormData();

        data.append("name", commentName);
        data.append("email", commentEmail);
        data.append("text", commentText);
        axios({
            method: 'post',
            url: '/api/Comment',
            data: data,
        })
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => { throw err });

        this.setState({ name: "", email: "", text: "" });
        
    }

    render() {
        return (
            <section>
                <form id="my-form" onSubmit={this.onSubmit}>
                    <a id="feedback-btn" type="submit">Нам важлива ваша думка</a>
                    <label htmlFor="in_name">Ім'я:</label>
                    <input id="in_name" type="text" onChange={this.onNameChange}/>
                    <label htmlFor="in_email">Email:</label>
                    <input id="in_email" type="email" onChange={this.onEmailChange}></input>
                    <label htmlFor="text_feedback">Коментар:</label>
                    <textarea name="feedback" id="text_feedback" onChange={this.onTextChange}></textarea>
                    <button type="submit">Залиште відгук</button>
                </form>
            </section>
        )
    }
}

Modified CommentController:
C#:
[HttpPost]
        public IActionResult Post([FromQuery]Comment comment)
        {

            comment.Id = Guid.NewGuid().ToString();

            return Ok(comment);
        }
 
Considering that you only set the Id in your controller method, why are you surprised?

Also, C# is case sensitive. It looks like your JavaScript is sending form data with lowercase field names, while your Comment class has Pascal case field names.
 
Back
Top Bottom