简体   繁体   中英

Can't send POST request from react method

I am creating a FB like app with Django and react. In the main page there's a feed where users can create posts and post them to the feed.

I am trying to implement the delete post functionality but I am running into some difficulties.

The logic is: The user clicks on the delete button on a post and the Browser sends and XMLHttpeRequest to the server to delete that post.

Here's the react component:

class Feed extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      profile_pic: profile_pic_url,
      user: username,
      posts: posts_from_server,
    }
  }

  handleClick() {
    const text = document.querySelector('#new_post_text').value;
    if (text.length > 1) {
      const data = {author: username, text: text}
      // send that post to the server to save it
      const csrftoken = Cookies.get('csrftoken');
      const request = new XMLHttpRequest();
      request.open('POST', '/create_new_post', true);
      request.setRequestHeader('X-CSRFToken', csrftoken);
      request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
      request.onload = () => {
        const response = JSON.parse(request.responseText)
        this.setState({
          posts : [{author: response.author, author_picture: profile_pic_url, text: response.text, date: response.date}, ...this.state.posts]
        })
        document.querySelector("#new_post_text").value = '';
        console.log(response)
      }
      request.send(JSON.stringify(data))
    }
  }

  deletePost(post_id, author) {
    const post = document.getElementById(post_id)
    post.style.animationPlayState = 'running';
    setTimeout(() =>{
      this.setState({
        posts: this.state.posts.filter(post => post.id != post_id)
      })
    }, 1000)

    // delete the post from the server
    const data = {'post_author': author, 'id': post_id}
    const csrftoken = Cookies.get('csrftoken');
    const request = new XMLHttpRequest();
    request.open('POST', '/delete_post', true);
    request.setRequestHeader('X-CSRFToken', csrftoken);
    request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    request.onload = () => {
      response = JSON.parse(request.responseText);
      console.log(response)
    }
    request.send(JSON.stringify(data))
    }

  
  render() {
    return (
      <div>
        <Post_generator 
          current_user={this.state.user}
          picture={this.state.profile_pic}
          onClick={() => this.handleClick()} />

        {this.state.posts.map(post => <Post
          onClick={() => this.deletePost(post.id, post.author)} 
          key={post.id}
          post_id={post.id}
          current_user={this.state.user}
          user={post.author}
          profile_pic={post.author_picture}
          text={post.text}
          date={post.date}  
        />)}
      </div>
    )
  }
}

this is urls.py:

from django.urls import path
from . import views


urlpatterns = [
    path('', views.index, name='login'),
    path('login', views.login_view, name='login'),
    path('index', views.index, name='index'),
    path('register', views.register_view, name='register'),
    path('logout', views.logout_view, name='logout'),
    path('profile', views.profile, name='profile'),
    path('change_profile_pic', views.change_profile_pic, name='upload_profile_pic'),
    path('create_new_post', views.create_new_post, name='create_new_post'),
    path('<str:friend>', views.friends_profile, name='friends_profile'),
    path('delete_post', views.delete_post_function, name='delete_post'),
]

and these are the views in views.py handling the two requests:

@login_required
@require_http_methods(['POST'])
def create_new_post(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    new_post = Post(author=request.user, text=data['text'])
    new_post.save()
    data['date']= new_post.date
    return JsonResponse(data)


# delete post 
@login_required
@require_http_methods(['POST'])
def delete_post_function(request):
    print('sdfgdfsghdsfkgjsdklfg')
    response = {"response": "data arrived to server"}
    return JsonResponse(response)

The thing that is giving me trouble is the deletePost() method... When it is executed I get a 405 error in the console.

The funny thing is that the XMLHTTPRequest in the handleClick method works just fine

Ok I figured it out...if the delete_post path in urls.py is not at the end of the urlspatterns list the code works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM