我正在我的 Android 设备上运行我的应用程序,并且没有使用任何模拟器。从邮递员我可以调用django Rest框架中定义的API,但是,当从前端调用它们时,我收到以下错误: AxiosError:网络错误
设置.py:
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cadence',
'rest_framework_simplejwt',
'rest_framework',
'corsheaders',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True
SpitifyViews.py:
class SpotifyViews(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def create_spotify_token(request):
try:
url = 'https://accounts.spotify.com/api/token'
headers = {
"content-type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
"client_id": "{my client id}",
"client_secret": "{my client secret}"
}
encoded_data = urlencode(data)
response = requests.post(url, headers=headers, data=encoded_data)
if response.status_code == 200:
return JsonResponse(response.json())
else:
return JsonResponse({"error": "Failed to get Spotify token"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as error:
return JsonResponse({"error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
JS代码:
axios.defaults.baseURL = "http://localhost:8000/";
export const sendRequest = async (method, endpoint, body) => {
const response = await axios.request({
method: method,
url: endpoint,
data: body,
headers: {
// Authorization: `Bearer ${localStorage.getItem("token")}`,
},
});
if (response.status === 401) {
// do somethinhg
}
return response;
};
const handleSignUp = async () =>{
console.log("signed up")
router.push("/login")
if(!info.email || !info.username || !info.password){
Alert.alert("Error", "All fields are required")
return
}
setIsSubmitting(true)
console.log(info)
try{
const response = await sendRequest(requestMehods.POST, "cadence/api/user/register/", {
...info,
});
console.log("response")
if (response.data.status === "success") {
// do somethinhg
router.push("/registration")
}
} catch (error){
console.log(error)
} finally {
setIsSubmitting(false)
}
};
知道可能是什么原因吗?
要将 React Native 连接到 Django 服务器,请在您的 IP 而不是本地主机上运行服务器。假设你的 IP 是 10.0.0.49
python manage.py runserver 10.0.0.49:8000
然后将前端baseURL更改为
axios.defaults.baseURL = "http://10.0.0.49:8000/";
不久前我的 django rn 项目也遇到了这个问题,非常令人沮丧