Home > Software engineering >  How can I post method in axios
How can I post method in axios

Time:08-29

I have created with Movie Db Api Movie App. Everything is okey in this project. Just i want to post rate which i selected movie. For example i add rating number for movie (4.5 or 8 ) and submit button. But there is error, and i cant this. How can i do this post? What is the right way?

import React, { useState } from 'react'
import axios from 'axios';
import { API_KEY } from '../api';
import { useParams } from 'react-router-dom';
const RateMovie = () => {

    const { id } = useParams()

    const [ rate, setRated ] = useState('')

    const rateMovie = async (e) => {
        e.preventDefault();
        console.log("Searching");
        try {
          const response = await axios.post(`https://api.themoviedb.org/3/movie/${id}/rating?api_key=${API_KEY}`, rate);
          console.log(response.data);
          console.log(rate);
          setRated('')
        } catch (error) {
          console.error(error);
        }
      };
    
      const handleChange = (e) => {
        setRated(e.target.value);
      };
    
  return (
    <form onSubmit={rateMovie}>
        <input type="number" onChange={handleChange} value={rate}/>
        <button type='submit' >Rate</button>
    </form>
  )
}

export default RateMovie

CodePudding user response:

The second param of axios post according to the docs

https://axios-http.com/docs/post_example

Is the param object.

According the MovieDB Api docs. https://developers.themoviedb.org/3/movies/rate-movie

The movie rating should be keyed under value.

const response = await axios.post(apiUrl, { value: rate });

CodePudding user response:

const response = await axios.post(apiUrl, { value: rate },{headers:{"Content-Type":"application/json;charset=utf-8"},params:{api_key:"your api key here"}});

You need to provide Content-Type header and api_key as query param. If you see the API documentation, you will notice that these two things are required. https://developers.themoviedb.org/3/movies/rate-movie

Also the request body is a json object which will only contain a property value.

  • Related