'POST' 数据到 Django 服务器后,Javascript 获取 api 没有得到响应

标签 javascript django reactjs django-rest-framework fetch-api

我正在构建一个基于 django 和 react 的投票应用程序。当我使用 fetch api 将数据发布到我的 django 服务器时,我返回一些详细信息以便我可以做其他事情。我正在使用 fetch api 来处理所有 GET和我前端的 POST 方法。这是我的表单类。

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>
    );
  }
}

这是我的 django View 函数:

@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"})

我使用 django rest 框架来执行此操作。在我将数据发布到后端后,服务器显示了一个 http 200 状态代码。所以我真的不知道我哪里错了。

最佳答案

您的 header 中缺少某些内容。 你需要明确地告诉你的请求是 AJAX 'X-Requested-With': 'XMLHttpRequest'

否则,作为 CORS 安全的一部分,“飞行前”请求会在实际 POST 请求之前完成,这解释了您在服务器上看到的“http 200 状态代码”。这是对此“飞行前”请求的响应。

参见 Django documentation on ajaxStack overflow about x-requested-with header

(编辑以添加链接描述)

关于 'POST' 数据到 Django 服务器后,Javascript 获取 api 没有得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278109/

相关文章:

python - django 未加载应用程序模板

python - Pydev 中的 Django 会产生多个进程?

python - 如何在HTML音频源标签中链接Django模型的属性?

javascript - 在 div 中动态插入 React 组件

javascript - 如何从 DOM 元素获取 Ext JS 组件

javascript - jQuery 用于设置具有选定单选值的输入类型的值

javascript - 优化逻辑以部分匹配 2 个数组项

reactjs - 属性 '[Symbol.observable]' 在类型 'Store<ApplicationState>' 中缺失,但在类型 'Store<any, AnyAction>' 中需要。 TS2741

javascript - TypeScript 变量范围与 JavaScript 变量范围

javascript - 如何重命名克隆表单中的所有 id (javascript)?