【发布时间】: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"}
]
【问题讨论】:
标签: json laravel react-native post axios