问题
I have these JSON Objects that I want to send to my API so I can save them on my database :
JSON Objects
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"}
],
}
Post request from 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);
}
};
When I submit with the function I have a 500 error code
Laravel controller:
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"
]);
}
When I try send this with Insomnia it's working, so how should I do ?
[
{ "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:
create a service via Fetch API in React-Native in same or in different in a different file i.e. 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),
});
}
then import and it call it inside your component
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
}) ;
};
来源:https://stackoverflow.com/questions/65794260/how-to-send-json-object-from-react-native-to-laravel-server