我正在构建一个非常简单的 api 和 react-native 应用程序。服务器运行良好(使用 PostMan 测试),但应用程序不调用服务器。当 axios 必须发送 post 请求时它会阻塞(见下文)。
我很绝望:-(浪费太多时间了。拜托,如果你能帮助我……
这是我的代码登录页面。它派遣动作创建者(使用 redux)提供电子邮件和密码:
...
const LogIn = React.createClass({
submitLogin() {
// log in the server
if (this.props.email !== '' && this.props.psw !== '') {
if (this.props.valid === true) {
this.props.dispatch(logIn(this.props.email, this.props.psw));
} else {
this.props.dispatch(errorTyping());
}
}
},
...
电子邮件和密码被检索并发送给动作创建者:
import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
return function (dispatch) {
console.log(email);
console.log(password);
console.log(SIGNIN_URL);
return axios.post(SIGNIN_URL, { email, password })
.then(
(response) => {
console.log(response);
const { token, userId } = response.data;
dispatch(authUser(userId));
}
)
.catch(
(error) => {
console.log('Could not log in');
}
);
};
};
const authUser = (userId) => {
return {
type: 'AUTH_USER',
userId
};
};
...
axios 之前的三个console.log() 以正确的方式显示数据。 SIGNIN_URL 与我在邮递员中使用的完全相同。 …但是 axios 没有调用。
只是为了给所有的卡片,这是我的商店:
import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
const store = createStore(reducer, initialState, compose(
applyMiddleware(thunk),
autoRehydrate()
));
persistStore(store, { storage: AsyncStorage });
return store;
};
调试器中没有错误消息(但是 axios 调用给出的错误消息(’Could not log in’)
我在 Windows 10 上,有:
"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"
即使我准备一个简单的 GET 调用并且服务器应该返回一个简单的消息(使用邮递员和浏览器测试),调用也会失败:
exports.test = () => {
return function () {
return axios.get('https://localhost:3000/v1/test')
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
最后,我还尝试修改添加标题的调用,如下所示,因为 api 被编码为接受 json:
const head = {
headers: { 'Content-Type': 'application/json' }
};
exports.test = () => {
return function () {
return axios.get('https://api.github.com/users/massimopibiri', head)
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
但即使这样也没有用。希望有人能帮助我。其他类似问题没有。
原文由 Pibo 发布,翻译遵循 CC BY-SA 4.0 许可协议
该解决方案来自不同的来源,但我将其发布在这里以帮助其他寻找相同问题的人。基本上我使用 Android AVD(模拟器)来构建应用程序。但模拟器实际上是另一台机器,这就是它无法调用本地主机的原因。
为了解决问题,我必须通过以下方式发送请求:
代替: