Node.js 收到一份;无法获取/登录";导航到路线时出错";http://127.0.0.1:8080/login" 在我的实时服务器上&引用;“新产品管理启动”;不过工作还不错
我已经构建了一个应用程序,该应用程序在由npm start命令生成的服务器上运行良好,但是当我使用npm live server或python simple HTTPserver设置服务器时,当我导航到/login路径时会出现此错误 说“无法获取/登录”。但在任何情况下,我都不会发送一个get请求。当我导航到/login路径时,应该显示的只是一个表单,它接收用户信息并发送post请求以获取令牌 以下是我的UserActions.js文件中的所有用户操作。正如您所看到的,它非常小(我甚至没有一个/register,这是因为我在数据库中只有一个admin用户,不需要注册) usrerActions.jsNode.js 收到一份;无法获取/登录";导航到路线时出错";http://127.0.0.1:8080/login" 在我的实时服务器上&引用;“新产品管理启动”;不过工作还不错,node.js,reactjs,express,axios,react-router-dom,Node.js,Reactjs,Express,Axios,React Router Dom,我已经构建了一个应用程序,该应用程序在由npm start命令生成的服务器上运行良好,但是当我使用npm live server或python simple HTTPserver设置服务器时,当我导航到/login路径时会出现此错误 说“无法获取/登录”。但在任何情况下,我都不会发送一个get请求。当我导航到/login路径时,应该显示的只是一个表单,它接收用户信息并发送post请求以获取令牌 以下是我的UserActions.js文件中的所有用户操作。正如您所看到的,它非常小(我甚至没有一个/
import {
SET_USER,
SET_ERRORS,
CLEAR_ERRORS,
LOADING_UI,
SET_UNAUTHENTICATED
} from "../types";
import axios from 'axios'
export const loginUser = (userData, history) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios
.post("/login", userData)
.then((res) => {
const FBIdToken = `Bearer ${res.data.token}`;
localStorage.setItem("FBIdToken", `Bearer ${res.data.token}`);
axios.defaults.headers.common['Authorization'] = FBIdToken;
// dispatch(getUserData());
dispatch({ type: CLEAR_ERRORS })
history.push("/");
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data
})
});
}
export const logoutUser = () => (dispatch) => {
localStorage.removeItem('FBIdToken');
delete axios.defaults.headers.common['Authorization'];
dispatch({ type: SET_UNAUTHENTICATED })
}
export const getUserData = () => (dispatch) => {
axios.get('/user')
.then(res => {
dispatch({
type: SET_USER,
payload: res.data
})
})
.catch(err => console.log(err));
}
我的app.js与路线
...
const token = localStorage.FBIdToken;
if (token) {
const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) {
store.dispatch(logoutUser());
window.location.href = "/login";
} else {
store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common["Authorization"] = token;
}
}
function App() {
document.documentElement.classList.remove("nav-open");
React.useEffect(() => {
document.body.classList.add("index");
return function cleanup() {
document.body.classList.remove("index");
};
});
return (
// <MuiThemeProvider theme={theme}>
<Provider store={store}>
<Router>
<div className="main">
<Switch>
<Route exact path="/" component={home} />
<Route exact path="/products" component={products} />
<Route exact path="/retreats" component={retreats} />
<Route exact path="/tarot" component={tarot} />
<Route
path="/artist"
render={props => <ProfilePage {...props} />}
/>
<Route exact path="/login" component={login} />
</Switch>
</div>
<Footer />
</Router>
</Provider>
// </MuiThemeProvider>
);
}
export default App;
所以我假设您使用的是react路由器dom。您正在使用?或者您正在使用另一种实际发送get请求的方式,例如标记?
React Router Dom需要您使用其组件在事物的React端导航。当运行live server时,当从浏览器发出请求时,“/login”不会调用您的React代码,而是调用您的节点服务器端点并尝试查找“/login”GET,因为来自浏览器选项卡的请求是一个GET请求。确保您的节点服务器
http://127.0.0.1:8080/
呈现index.html页面,其中连接了react app.js。嘿,谢谢,我明白你的意思了。但我仍然不太明白如何更改代码。我是否应该更改App.js路由以执行此操作?或者你是说在我背后?那会去哪里?你能检查一下你的NPMStart命令实际上做了什么吗?通常,当我们使用react with node时,我们要做的是在特定端口上运行node.js API,然后从静态文件夹呈现index.html文件,您是否将react代码库放置在通过node呈现的静态文件夹中?npm live server只提供可用内容,npm start可能正在为您创建react捆绑包。。。我不认为在这里使用npm live server是正确的选择。在服务器中启动应用程序之前,我使用了“npm run build”来构建应用程序。这就是错误出现的时候。这两个脚本都是createreact应用程序附带的默认脚本。我还尝试了一个有同样问题的python服务器。
import React, { Component } from "react";
...
export class login extends Component {
constructor(){
super();
this.state = {
email: '',
password: '',
errors: {}
}
}
componentWillReceiveProps(nextProps) {
if(nextProps.UI.errors) {
this.setState({ errors: nextProps.UI.errors })
}
}
handleSubmit = (event) => {
event.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
}
this.props.loginUser(userData, this.props.history);
}
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
// loading was before: { classes, UI: { loading } }
const { classes, loading } = this.props;
const { errors } = this.state;
return (
<>
<IndexNavbar />
<ProfilePageHeader />
<Grid container className={classes.form}>
<Grid item sm />
<Grid item sm>
<ChangeHistoryIcon />
<Typography variant="h3" className={classes.pageTitle}>
Login
</Typography>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="email"
name="email"
type="email"
label="Email"
className={classes.textField}
helperText={errors.email}
error={errors.email ? true : false}
value={this.state.email}
onChange={this.handleChange}
fullWidth
/>
<TextField
id="password"
name="password"
type="password"
label="Password"
className={classes.textField}
helperText={errors.password}
error={errors.password ? true : false}
value={this.state.password}
onChange={this.handleChange}
fullWidth
/>
{errors.general && (
<Typography variant="body2" className={classes.customError}>
{errors.general}
</Typography>
)}
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
>
Login
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
</form>
</Grid>
<Grid item sm />
</Grid>
</>
);
}
}
login.propTypes = {
classes: PropTypes.object.isRequired,
loginUser: PropTypes.func.isRequired,
user: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI
});
const mapActionsToProps = {
loginUser
}
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(login));
const functions = require('firebase-functions');
const app = require('express')();
const FBAuth = require('./util/fbAuth')
const cors = require('cors');
app.use(cors());
const { getAllPosts, createOnePost, getThePost, deletePost, uploadImage } = require('./handlers/posts');
const { login } = require('./handlers/users');
// Posts Routes
app.get('/posts', getAllPosts);
app.get('/post/:postId', getThePost);
app.post("/post", FBAuth, createOnePost);
app.delete('/post/:postId', FBAuth, deletePost);
app.post('/post/:postId/image', FBAuth, uploadImage);
//TODO update post
// Login Route
app.post('/login', login)
exports.api = functions.https.onRequest(app)