简体   繁体   中英

how do I send a text field input from the frontend to the backend

I have made a website, it uses react as the frontend and Django as the backend. I am trying to get input from the frontend and send it to the backend, it doesn't seem to be working. the problem is that when I try to print it the text input sent from the front end is not being printed. here's the code:

searchSong(e) {
    this.setState({
        search: e.target.value
    });
    console.log(this.state.search)
}

this is what makes the text field input:

                <TextField id="outlined-basic" label="Song" variant="outlined" value={this.state.search} onChange={this.searchSong} />
                <Button variant="contained" color="secondary" onClick={this.addButtonPressed}>Search Song</Button>

these are the functions that send the text input from the frontend to the backend and the states:

addButtonPressed() {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      search: this.state.search,
    })
  };
  fetch("/spotify/search-song/", requestOptions)
}

searchSong(e) {
    this.setState({
        search: e.target.value
    });
    console.log(this.state.search)
}

the state:

  this.state = {
      search: ""
  }

here's the function that I made which will test if I got the correct text field input:

def search_song(session_id, song_name):
    search_letters = "playlist/?type=" + song_name
    print(search_letters)

this is the view that uses the function:

class SearchSong(APIView):
    lookup_url_kwarg = 'search'
    def post(self, request, format=None):
        if not request.session.exists(request.session.session_key):
            request.session.create()
        room_code = self.request.session.get(self.lookup_url_kwarg)
        music = str(request.data.get(self.lookup_url_kwarg))
        room = Room.objects.filter(code=room_code)[0]
        search_song(room.host, music)

this is the endpoint being called by the frontend:

from django.urls import path
from .views import *

urlpatterns = [
    path('search-song', SearchSong.as_view())
]

Try this:

in your urls.py :

from django.urls import path
from .views import *

    urlpatterns = [ ⬇⬇
    path('search-song/', SearchSong.as_view())

]

SearchSong.js: Give full path with '/'

addButtonPressed() {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      search: this.state.search,
    })
  };    ⬇⬇⬇⬇⬇                                    ⬇⬇⬇
  fetch("http://127.0.0.1:8000/spotify/search-song/", requestOptions)
}

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