我的错误来自前端:
Login.js:44 POST http://localhost:8016/ 404 (Not Found)
这是我的Login.js
组件:
import React, { Component } from 'react'
import Router from 'next/router'
import { login } from 'next-authentication'
import { Button, Form, Grid, Header, Message, Segment } from 'semantic-ui-react'
// import PropTypes from 'prop-types';
class Login extends Component {
constructor(props) {
super(props)
this.state = {
isLoggedIn: false,
username: '',
password: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleIsLoggedInClick = this.handleIsLoggedInClick.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidMount() {
this.setState({})
}
handleChange(event) {
var { name, value } = event.target
this.setState({
[name]: value
})
}
handleIsLoggedInClick() {
var { isLoggedIn } = this.state
!isLoggedIn ? this.setState({ isLoggedIn: true }) : this.setState({ isLoggedIn: false })
}
async handleSubmit(event) {
event.preventDefault()
const { username, password } = this.state
try {
const response = await window.fetch('http://localhost:8016/', {
method: 'post',
body: JSON.stringify({ username, password }),
headers: { 'Content-Type': 'application/json' }
})
if (response.ok) {
const { token } = await response.json()
const loginOptions = {
token,
cookieOptions: { expires: 1 },
callback: () => Router.push('/users')
}
login(loginOptions)
} else {
// eslint-disable-next-line no-console
console.log('Login failed.')
}
} catch (error) {
console.log('Implementation or Network error.')
}
}
render() {
var { username, password, isLoggedIn } = this.state
return (
<div className='login-form'>
<style>
{`
body > div,
body > div > div,
body > div > div > div.login-form {
height: 100%;
}
`}
</style>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' color='teal' textAlign='center'>
{isLoggedIn ? `Register for an account` : ` Log-in to your account`}
</Header>
<Form size='large' onSubmit={this.handleSubmit}>
<Segment stacked>
<Form.Input
fluid
icon='user'
iconPosition='left'
placeholder='E-mail address'
name='username'
value={username}
onChange={this.handleChange}
/>
<Form.Input
fluid
icon='lock'
iconPosition='left'
placeholder='Password'
name='password'
value={password}
onChange={this.handleChange}
/>
<Button color='teal' fluid size='large'>
{isLoggedIn ? `Register` : `Log-in`}
</Button>
</Segment>
</Form>
{!isLoggedIn
? <Message>
New to us?
<a onClick={this.handleIsLoggedInClick} href='#'> Register!</a>
</Message>
: <Message>
<a onClick={this.handleIsLoggedInClick} href='#'>Back to Login</a>
</Message>
}
</Grid.Column>
</Grid>
</div>
)
}
}
export default Login
我已通过MongoCompass
检查了用户,但没有看到任何内容:
这是我的快速应用程序:
/* eslint-disable no-console */
/* eslint-disable no-shadow */
var express = require('express')
var next = require('next')
var session = require('express-session')
var MongoStore = require('connect-mongo')(session)
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var cors = require('cors')
// var morgan = require('morgan');
var HttpStatus = require('http-status-codes')
var PORT = process.env.PORT || 8016
var dev = process.env.NODE_ENV !== 'production'
var NextApp = next({ dev })
var handle = NextApp.getRequestHandler()
var mongoose = require('mongoose')
var db = `mongodb://127.0.0.1:27017/hillfinder`
function errorHandler (err, req, res, next) {
// Set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// Log error
console.error(err.stack)
// Render the error page
res.status(err.status || 500)
// Default error message by HTTP code
res.render('error', {
title: HttpStatus.getStatusText(err.status),
message: HttpStatus.getStatusText(err.status)
})
}
const users = require('./routes')
NextApp.prepare()
.then(() => {
const app = express()
mongoose.connect(db)
mongoose.Promise = global.Promise
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${db}`)
})
.on('error', err => {
console.log(`Connection error: ${err.message}`)
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// app.use(morgan('combined'));
app.use(cookieParser())
app.use(
session({
secret: 'very secret 12345',
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
)
app.use(cors())
// eslint-disable-next-line global-require
app.use('/', users)
app.get('*', (req, res) => {
return handle(req, res)
})
// eslint-disable-next-line func-names
app.use(errorHandler, function (error, req, res, next) {
res.json({ message: error.message })
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
.catch(err => {
console.error(err)
})
这是管理我所有路线server/routes/index.js
var router = require('express').Router();
router.use('/users', require('./users'));
module.exports = router;
这是我的用户路线server/routes/users
var router = require('express').Router()
var UserModel = require('../../models/UserModel')
router
.route('/')
.get(function (req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post((req, res) => {
UserModel.create({
username: req.email,
password: req.password
}, (err, user) => {
if (err) res.status(500).send(err)
res.json(user)
})
})
有什么建议吗?