【发布时间】:2019-03-06 13:30:03
【问题描述】:
我想知道是否有人可以在这里帮助我。我目前正在学习如何将数据库与我的服务器连接的 Udemy 课程。我一直在逐字逐句地检查老师的代码,经常检查我的代码是否有任何小错误。到目前为止,我的 server.js 文件上的代码没有任何问题。港口运行平稳。但是,当我从 Postman 运行 POST 请求时,我得到了
未处理的拒绝错误:连接意外终止
通过 Postman,我完全按照老师的做法进行操作。 POST 请求包含电子邮件、密码、名称,并且 localhost:3000/register 路径很好。这就是我的服务器所连接的。我想知道发生了什么,因为我的代码运行平稳,直到我发出 POST 请求。还注意到我在 Postman 上收到 200 OK 响应,但在服务器上,我收到未处理的拒绝错误消息。
是的,控制台日志是故意的,我完全按照他在视频中所做的事情进行,所以代码在下一个视频中必然会随着时间而改变。
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require ('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const pg = require('pg');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
port: '3000',
password : '',
database : 'smart-brain'
}
});
const app = express();
const database = {
users: [
{
id: '123',
name: 'Jess',
email: 'jess@gmail.com',
password: 'cookies',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Sally',
email: 'sally@gmail.com',
password: 'bananas',
entries: 0,
joined: new Date()
}
]
}
app.use(bodyParser.json());
//body parser is basically json.parse. we want to always parse json so our code is readable in string form. POST > Raw > JSON
app.use(cors())
app.get('/', (req, res)=> {
res.send(database.users);
})
app.post('/signin', (req, res) => {
if(req.body.email === database.users[0].email && req.body.password === database.users[0].password) {
res.json(database.users[0])
} else {
res.status(400).json('error logging in')
}
})
app.post('/register', (req, res) => {
const { email, name, password } = req.body;
db('users').insert({
email: email,
name: name,
joined: new Date()
}).then(() => console.log())
res.json(database.users[database.users.length-1])
});
app.get('/profile/:id', (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
return res.json(user);
}
})
if (!found) {
res.status(400).json('not found...')
}
})
//now we are creating route for entries count. everytime they submit image, they will get a count for it
app.put('/image', (req, res) => {
const { id } = req.body;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
user.entries++
return res.json(user.entries);
}
})
if (!found) {
res.status(400).json('not found...')
}
})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
【问题讨论】:
-
屏幕截图中的代码与您问题中的代码不同。哪个是正确的?
-
@Phil 底部的代码只是我的 javascript 文件中的整个代码,只是发布它以防有人发现我忽略的错误。对不起,我应该圈出我最麻烦的代码。在 app.post('/register'-- 部分,我遇到了最大的麻烦。我在视频中使用该代码进行操作,但仍然通过服务器收到错误。
标签: javascript postgresql postman