如何将 JSON 对象从 React Native 发送到 Laravel 服务器?
Posted
技术标签:
【中文标题】如何将 JSON 对象从 React Native 发送到 Laravel 服务器?【英文标题】:How to send JSON Object from React Native to Laravel Server? 【发布时间】:2021-04-23 21:58:54 【问题描述】:我有这些 JSON 对象想要发送到我的 API,以便我可以将它们保存在我的数据库中:
JSON 对象
const utility =
con: [
"name": "Michel", "phone": "+213 93 783 28 73", "users_id": "1",
"name": "Annie", "phone": "+213 93 783 28 72", "users_id": "1",
"name": "Rory", "phone": "+16505551212", "users_id": "1",
"name": "CESI", "phone": "+213 58 357 31 78", "users_id": "1"
],
来自 React Native 的发布请求:
export default function Contact( navigation )
const user, logout = useContext(AuthContext)
const [contact, setContact] = useState([]);
const [count, setCount] = useState('');
//console.log(utility.con)
const uticontact = utility.con;
console.log(uticontact)
const SubmitCon = async () =>
axios.defaults.headers.common['Authorization'] = `Bearer $user.token`;
try
axios.post(`/api/contact`,
data : JSON.stringify(utility.con)
);
console.log(`Contacts successfully added`);
catch (err)
console.log(err);
;
当我使用函数提交时,我有一个 500 错误代码
Laravel 控制器:
public function store(Request $request)
foreach ($request->json()->all() as $record)
$contact = new Contact();
$contact->name = $record['name'];
$contact->phone = $record['phone'];
$contact->users_id = $record['users_id'];
$contact->save();
return response()->json([
"code" => 200,
"message" => "Contacts added successfully"
]);
当我尝试使用 Insomnia 发送此邮件时,它正在工作,我应该怎么做?
[
"name": "Michel", "phone": "+213 93 783 28 73", "users_id": "1",
"name": "Annie", "phone": "+213 93 783 28 72", "users_id": "1",
"name": "Rory", "phone": "+16505551212", "users_id": "1",
"name": "CESI", "phone": "+213 93 783 28 73", "users_id": "1"
]
【问题讨论】:
【参考方案1】:通过 React-Native 中的 Fetch API 在相同或不同文件中创建服务 即service.js
const api_url = "www.myUrl.com/"
export function submitContact(data)
return fetch(api_url+'/api/contact',
method: 'POST',
headers :
'Accept' : 'application/json',
'Content-Type' : 'application/json',
,
body: JSON.stringify(data),
);
然后导入并在你的组件中调用它
import SubmitContact from './service'
export default function Contact( navigation )
const user, logout = useContext(AuthContext)
const [contact, setContact] = useState([]);
const [count, setCount] = useState('');
//console.log(utility.con)
const uticontact = utility.con;
console.log(uticontact)
//Send Post Request
submitContact(utility.con).then((response) => response.json())
.then((responseJson) =>
// perform some action on your response
) ;
;
【讨论】:
以上是关于如何将 JSON 对象从 React Native 发送到 Laravel 服务器?的主要内容,如果未能解决你的问题,请参考以下文章
使用 JavaScript React Native 从 API 的 json 对象中提取数据
如何将图像从JSON文件放到React Native Js页面
如何将处于新状态的json对象中的特定数据保存到react native中
react-native 如何从本地JSON文件中获取数据?