【问题标题】:how do I send a text field input from the frontend to the backend如何将文本字段输入从前端发送到后端
【发布时间】:2021-06-11 07:16:58
【问题描述】:

我做了一个网站,它使用 react 作为前端,Django 作为后端。我正在尝试从前端获取输入并将其发送到后端,它似乎不起作用。问题是当我尝试打印它时,没有打印从前端发送的文本输入。 这是代码:

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

这就是文本字段输入的原因:

                <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>

这些是将文本输入从前端发送到后端和状态的函数:

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

状态:

  this.state = {
      search: ""
  }

这是我创建的函数,它将测试我是否输入了正确的文本字段:

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

这是使用该函数的视图:

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)

这是前端调用的端点:

from django.urls import path
from .views import *

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

【问题讨论】:

  • 你能详细说明一下这里的问题吗,是不是报错了?
  • 不,当我尝试打印它时,从前端发送的文本输入没有被打印

标签: javascript python reactjs django


【解决方案1】:

试试这个:

在您的urls.py:

from django.urls import path
from .views import *

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

]

SearchSong.js:'/'

给出完整路径
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)
}

【讨论】:

    猜你喜欢
    • 2016-12-27
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2021-02-06
    • 2021-11-28
    • 2018-07-06
    相关资源
    最近更新 更多