我的代码很简单。我必须将表单数据发送到服务器。我的令牌也正在工作。但是我不能将表单数据作为数据发送。应该是:“ input”:“ message”,但这给了我非常复杂的东西。我的Axios似乎也不错,但我不确定。
const Screen = ({ navigation }) => {
const [formData, setFormData] = useState();
const onSubmit = async ({ formData }) => {
let token = await AsyncStorage.getItem("token");
const data = new FormData();
data.append("input", { input: formData });
axios
.post(
`http://example.com/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true",
},
}
)
.then((res) => {
console.log(res.data);
})
.catch((error) => {
console.log(error);
});
};
return (
<View>
<Input
value={formData}
onChangeText={setFormData}
placeholder="Type something"
onSubmitEditing={() => onSubmit({ formData })}
/>
</View>
);
};
export default Screen;
在表单数据部分,我的键是“输入”,我的值是用户编写的内容。就像:“ input”:“用户的消息”。 -但是它给出的数据是这样的:
FormData {
"_parts": Array [
Array [
"input",
Object {
"input": "Naber",
},
],
],
}
答案 0 :(得分:0)
像这样附加到formData上:
data.append("input",formData);
,您需要将标头Content-Type
作为multipart/form-data
发送,并使用axios发送formData,如下所示:
axios.post("api",data,{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "multipart/form-data",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true",
}
})
如果您随每个请求发送授权标头,则可以使用`axios.defaults.headers.common附加到所有axios req header
,如下所示:
axios.defaults.headers.common['Authorization'] =`Bearer ${token}`;