Reputation: 1231
I am using Axios JS library for sending post json request. but I am not receiving anything at the server. Here is my code
const dt = JSON.stringify({"data":{"value":"gdfg1df2g2121dgfdg"}});
const request = axios.post(url, {dt});
I need to send post raw body in json format.
Upvotes: 18
Views: 58546
Reputation: 1208
This worked for me.
const [formData, setFormData] = useState({ username: "", password: "" });
And this is onsubmit handle method
export const Login = () => {
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || "/home";
const [formData, setFormData] = useState({ username: "", password: "" });
const [error, setError] = useState("");
const API = axios.create({
baseURL: "http://localhost:9000",
});
const updateUserName = (e: any) => {
setFormData({ ...formData, username: e.target.value });
};
const updatePassword = (e: any) => {
setFormData({ ...formData, password: e.target.value });
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const config = { headers: { "Content-Type": "application/json" } };
try {
const res = await API.post("/authenticate", formData, config).then(
(res) => {
console.log(res?.data);
if (res?.data.token) {
const token = res?.data.token;
console.log("token: " + token);
navigate(from, { replace: true });
} else {
console.log("incorrect submission");
setError(res.data);
}
}
);
} catch (err) {
if (!err) {
setError("no server response");
} else {
setError("registeration failed");
}
}
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
User Name: <input type="text" onChange={updateUserName} />
Password: <input type="text" onChange={updatePassword} />
<button type="submit">Submit</button>
</form>
</div>
);
};
Upvotes: -3
Reputation: 911
You don't need to stringify your payload. Axios will do it for you when it it send a request.
const dt = { data: { value: "gdfg1df2g2121dgfdg" }};
const request = axios.post(url, dt);
Upvotes: 5
Reputation: 362
By default axios uses Json for posting data so you don't need to stringify your data. The problem could be that you're doing that. Could you try doing the post without it and check if it works? Also you don't need the curly braces to wrap your data unless that's the format of the object in your server. Otherwise could you give me information about how the body of the request looks like so I have more context? You can check that in chrome dev tools using the network tab
Upvotes: 15