我正在构建一个非常简单的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 正好是我在 postman 中使用的相同地址。...但 axios 没有调用。
只是为了将所有的牌都揭示出来,这是我的 store:
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 调用给出的“无法登录”消息)
我使用的是 Windows 10,并且安装了:
"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"
即使我准备了一个简单的GET请求,而服务器应该返回一个简单的消息(在Postman和浏览器中测试过),但调用仍然失败:
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');
}
);
};
};
但即使这样也没用。希望有人能帮助我。其他类似的问题也没有解决。