Попытка использовать данные API из бэкенда Django в React
Я пытаюсь использовать Bing web search api. У меня есть представление, настроенное в Django backend. Я смог получить данные о результатах поиска в терминале. Но я получаю ошибку при получении данных в React. Если бы вы могли помочь с подробным ответом, я был бы очень признателен! Заранее спасибо.
Терминал запуска сервера Django при обновлении страницы React:
'name': 'iPhone 13 review | Tom's Guide',
'noCache': False,
'primaryImageOfPage': {'height': 80,
'imageId': 'OIP.63KzaXCF-d8nPkQdmM6bWgHaDL',
'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1',
'width': 80},
'snippet': 'The<b> iPhone 13</b> is a great '
'budget-friendly flagship phone with a '
'brighter display, longer battery life and '
'powerful cameras. Read our in-depth '
'review to find out its strengths and '
'weaknesses, and how it compares to the '
'iPhone 14 and other models.',
'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1',
'url': 'https://www.tomsguide.com/reviews/iphone-13'}],
'webSearchUrl': 'https://www.bing.com/search?q=iphone+13'}}
Internal Server Error: /home/
Traceback (most recent call last):
File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
response = self.process_response(request, response)
File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
if response.get("X-Frame-Options") is not None:
AttributeError: 'list' object has no attribute 'get'
[22/Mar/2024 14:15:37] "GET /home/ HTTP/1.1" 500 72597
SearchResults.js React файл:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const SearchResults = () =\> {
const \[data, setData\] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(`http://localhost:8000/home/`);
setData(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
<h1>My Component</h1>
{data ? (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default SearchResults;
views.py внутри bing_api (папка app):
def home(request):
url = 'https://api.bing.microsoft.com/v7.0/search'
search_url = "https://api.bing.microsoft.com/v7.0/search"
search_term = 'iphone 13'
headers = {"Ocp-Apim-Subscription-Key": API_KEY}
params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()
data = response.json()
pprint(data)
#below is to view in React
pages = search_results['webPages']
results = pages['value']
# pprint(results\[0\])
return results
url.py folder:
from django.urls import path
from . import views
urlpatterns = \[
path('home/', views.home, name='home'),
\]