【发布时间】:2020-03-28 04:45:23
【问题描述】:
我正在尝试从我的 React 本机应用程序向本地服务器 POST 请求,但出现错误。
我构建了一个通用的httpMethod函数
export async function httpMethod(req) {
try {
var response = fetch(`${apiUrl}${req.api}`, {
method: req.method,
headers: req.headers
? req.headers
: {
'Content-Type': 'application/json'
},
body: JSON.stringify(req.body)
});
return response;
} catch (error) {
console.error(error);
}
}
我从这个方法中调用它:
export async function registerUser(props) {
try {
const { email, password } = props;
let api = `/users`;
return await httpMethod({
method: 'POST',
api,
body: { email, password }
});
} catch (error) {
console.error(error);
}
}
网址是http://0.0.0.0:9000/users
添加一些控制台日志以确保我的 HTTP 请求 URL 和参数正常后,我收到此错误:
HTTP POST request to -- http://0.0.0.0:9000/users
req.body: {"email":"Test@gmail.mmm","password":"@Aa123456"}
headers: undefined
Network request failed
- node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:15 in XMLHttpRequest.xhr.onerror
- node_modules\event-target-shim\lib\event-target.js:172:38 in XMLHttpRequest.dispatchEvent
- ... 9 more stack frames from framework internals
我做错了什么?
【问题讨论】:
-
我认为您需要定义您的请求标头,看起来您在代码中将标头定义为至少
content-type: application/json,但它们在您的控制台中显示为undefined日志。 -
尝试使用你的IP地址IP_ADDRESS:9000/users而不是0.0.0.0:9000/users
标签: javascript react-native http fetch