1

I am building a poll app based on django and react.When I use fetch api to POST data to my django server,I return some detail information so that I can do something else.I am using fetch api to handle all GET and POST method on my front end.This is my form class.

export default class VoteForm extends React.Component{
  constructor(props){
    super(props);
    this.state = {subjects:[],choosen:"",new:false,message:''};
    this.handleSelect = this.handleSelect.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleNewOption = this.handleNewOption.bind(this);
  }
  componentWillReceiveProps(props){
    this.setState({subjects:props.subjects});
    this.setState({choosen:props.subjects[0]});
  }
  handleSelect(event){
    if(event.target.value=="customize new option"){
      this.setState({new:true});
    }else{
      this.setState({choosen:event.target.value,new:false});
    }
  }
  handleNewOption(event){
    console.log(event.target.value);
    this.setState({choosen:event.target.value});
  }
  handleSubmit(){
    let json = {
      pk:this.props.pk,
      subject:this.state.choosen,
    };
    let csrftoken = Cookies.get('csrftoken');
    let header = {
      "method":'POST',
      "body" :JSON.stringify(json),
      "credentials": 'include',
      "headers":{
      "X-CSRFToken": csrftoken,
      "Accept": "application/json",
      "Content-Type": "application/json",
      }
    };

    //This is where it gets wrong.Both alerts didn't work.It only prompted the small window a few times after I quickly clicked the mouse several times.And response wasn't consoled either.

    fetch('/voteapp/addvoteforsubject/ ',header)
    .then(function(response){
      alert("get response");
      return response.json();
    })
    .then(function(response){
      //console.log(response);
      alert(response.detail);
    })
    .catch(function(error){
      console.log(error);
    });


  }
  render(){
    let Options = this.state.subjects.map((opt,index)=>(<option key={index}>{ opt }</option>));
    let new_input;
    let submit;
    if(this.state.new){
       new_input = (<input type="text" className="form-control" placeholder="type new option" onChange={this.handleNewOption}></input>);
       submit = (  <button className="btn btn-secondary btn-block" onClick={this.handleSubmit}>Submit</button>);
    }else{
       submit = (  <button className="btn btn-secondary btn-block" onClick={this.handleSubmit}>Submit</button>);
    }
    return (
      <form>
        <label>Select</label>
        <select className="form-control" onChange={this.handleSelect}>
          <option selected disabled>Choose your option</option>
          { Options }
          <option>customize new option</option>
        </select>
        { new_input }
        { submit }
      </form>
    );
  }
}

This is my django view function:

@api_view(['GET','POST'])
def vote_or_not(request):
    if request.method == 'GET':
        return Response(data={'message':'Get data'})
    if request.method == 'POST':
        vote = VoteTitle.objects.get(pk=request.data['pk'])
        if request.user.is_authenticated():
            if Votes_ip.objects.filter(vote_title=vote,ip_address=request.META['REMOTE_ADDR']).count()== 0 and Votes.objects.filter(voter=request.user,vote_title=vote).count()==0:
                a = Votes_ip.objects.create(vote_title=vote,ip_address=request.META['REMOTE_ADDR'])
                b = Votes.objects.create(voter=request.user,vote_title=vote)
                subject = vote.subjects.get_or_create(name=request.data['subject'])[0]
                subject.votes += 1
                subject.save()
                print("Not Voted")
                return Response(data={'detail':'succeed'})
        elif Votes_ip.objects.filter(vote_title=vote,ip_address=request.META['REMOTE_ADDR']).count() ==0:
            a = Votes_ip.objects.create(vote_title=vote,ip_address=request.META['REMOTE_ADDR'])
            subject = vote.subjects.get_or_create(name=request.data['subject'])[0]
            subject.votes += 1
            subject.save()
            print("Not Voted")
            return Response(data={'detail':'succeed'})
        print("Voted")
        return Response({'detail':"you have created once"})

I use django rest framework to do this.The server showed a http 200 status code after I posted data to backend.So I really don't know where I got wrong.

Philipl
  • 395
  • 4
  • 21

1 Answers1

1

Your are missing something in your headers. You need to explicitly tell your request is AJAX with 'X-Requested-With': 'XMLHttpRequest'

Without this, as part of CORS security, a "pre-flight" request is done before the actual POST request, which explains the "http 200 status code" you see on your server. It's the response to this "pre-flight" request.

See Django documentation on ajax And Stack overflow about x-requested-with header

(edited to add link descriptions)

Nadège
  • 931
  • 6
  • 12