admin管理员组

文章数量:1399936

I have a problem where I have a user click on a link "/[email protected]". The user is showed a option to make a comment and rate the movie. But when Sending the information, I keep getting the

movie-details.js:69
POST https://localhost:7007/api/comments 405 (Method Not Allowed)
movie-details.js:85 Error: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input
at movie-details.js:79:36 

same with rating.

Here is my code:

  public class CommentDto
  {
      public string Text { get; set; }
      public DateTime CreatedDate { get; set; }
      public string UserName { get; set; }
      public int MovieId { get; set; }
  }

  public class CommentCreateDto
  {
      public int MovieId { get; set; }
      public string Text { get; set; }
  }

  public class RatingDto
  {
      public int Value { get; set; }
      public DateTime CreatedDate { get; set; }
      public string UserName { get; set; }
  }

  public class RatingCreateDto
  {
      public int MovieId { get; set; }
      public int Value { get; set; }
  }

movie-details.js

async function submitComment() {
    const commentText = document.getElementById('commentText').value;

    try {
        const response = await fetch('/api/comments', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                movieId: currentMovieId,
                text: commentText
            })
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.error || "Neznámá chyba");
        }

        alert("Komentář uložen: " + data.message);
        loadComments();

    } catch (error) {
        console.error("Chyba:", error);
        alert("Chyba: " + error.message);
    }
}

function submitRating() {
    const ratingValue = document.getElementById('ratingValue').value;

    fetch('/api/ratings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            movieId: parseInt(new URLSearchParams(window.location.search).get('id')),
            value: ratingValue
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadRatings();
            }
        })
        .catch(error => console.error('Error:', error));
}

And the CommentController.cs:

 [ApiController]
 [Route("api/[controller]")]
 

 public class CommentsController : ControllerBase
 {
     private readonly ApplicationDbContext _context;

     public CommentsController(ApplicationDbContext context)
     {
         _context = context;
     }

     [HttpGet]
  
     public async Task<ActionResult<IEnumerable<CommentDto>>> GetComments(int movieId)
     {
         return await _context.Comments
             .Where(c => c.MovieId == movieId)
             .Include(c => c.User)
             .Select(c => new CommentDto
             {
                 Text = c.Text,
                 CreatedDate = c.CreatedDate,
                 UserName = c.User.UserName
             })
             .ToListAsync();
     }

     [HttpPost]
     public async Task<IActionResult> AddComment([FromBody] CommentCreateDto comment)
     {
         if (comment == null)
         {
             return BadRequest("Invalid comment data.");
         }
       
         await _context.Comments.AddAsync(new Comment
         {
             Text = comment.Text,
             UserId = comment.UserName,
             MovieId = comment.MovieId,
             CreatedDate = DateTime.UtcNow
         });
         await _context.SaveChangesAsync();

         return Ok("Comment added successfully.");
     }

 }

(Similar with rating)

I've tried Disabling authorization, didn't help. I want it to asign the comment and rating to the logged user and send it to the database.

本文标签: javascript405 Method Not Allowed when Posting Comments and Ratings in ASPNET Core APIStack Overflow