我正在使用Nodejs和MySQL作为数据库来构建注册应用程序。因此,当我运行脚本时,它会在“ localhost:3000 / register”上显示“注册成功”消息,并且还将数据也添加到表中。但是,当我尝试通过API发送数据时,会提示我“无法发布/注册”。 我在代码中找不到错误。请帮助我。
我也正在使用body-parser来连接API请求。我也使用XAMPP。这是我的代码;
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const router = express.Router();
const bcrypt = require('bcrypt');
const saltRounds = 10;
// create connection to the database
const db = module.exports = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'pulse'
});
//connecting
db.connect((err) =>{
if(err){
throw err;
}
console.log('MySql connected...');
});
const app = module.exports = express();
app.use(bodyParser.urlencoded({extended: true})); //Accept URL Encoded params
app.use(bodyParser.json()); //accept JSON Params
//create user Table
app.get('/createUser',(req,res)=>{
let sql = 'CREATE TABLE users(id int AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), dateOfBirth VARCHAR(255), password VARCHAR(255), PRIMARY KEY(id))';
db.query(sql,(err,result)=>{
if(err) throw err;
console.log(result);
res.send('User table created');
});
});
//register user
app.get('/register',(req,res,next)=>{
const post_data = req.body;
const name = post_data.name;
const email = post_data.email;
const dateOfBirth = post_data.date;
const password = post_data.password;
let userEmail = {'email':email};
let sql = 'SELECT * FROM users WHERE ?';
let query = db.query(sql,userEmail, (err,result)=>{
if(err) throw err
//console.log('[MySQL ERROR',err);
if(result && result.length) {
res.json('User already exists');
}
else{
let insertUser = {'name':name, 'email':email, 'dateOfBirth':dateOfBirth, 'password':password};
let sql = 'INSERT INTO users SET ?';
let query = db.query(sql,insertUser,function(err,result){
if(err) throw err;
res.json('Registration successful');
});
}
});
});
//creating the server
app.listen('3000', () => {
console.log("Server started on port 3000");
});
本地浏览器“ localhost:3000 / register”的结果为“注册成功”,并且在表中添加了一行。
bur in API,
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /register</pre>
</body>
</html>
答案 0 :(得分:2)
您正在发送发帖请求,但您的端点为app.get('/register')
,可以将其更改为发帖。
app.get('/register') // this's get
//if you want to use it as post change it to
app.post('/register', (req, res) => {...})
要将请求发送到端点,您可以使用类似的形式,因为您不能直接从浏览器访问POST
<form action="/register" method="post">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
或使用jQuery post
$.post('/register', { name: "John", time: "2pm" }, (response) => console.log(response) );
答案 1 :(得分:2)
您必须编写一个“ POST”端点来解析请求正文。
function getLocalIP: string;
var
IPList: TIdStackLocalAddressList;
IPStrings: TStringList;
i: integer;
begin
Result := '';
try
IPList := TIdStackLocalAddressList.Create;
try
TIdStack.IncUsage;
try
GStack.GetLocalAddressList(IPList);
finally
TIdStack.DecUsage;
end;
if IPList.Count > 0 then
begin
WriteLog('DEBUG', 'No of Addresses: ' + IntToStr(IPList.Count));
IPStrings := TStringList.Create;
try
for i := 0 to IPList.Count - 1 do
begin
if IPList[i].IPVersion = Id_IPv4 then
begin
IPStrings.Add(IPList[i].IPAddress + ':' + TIdStackLocalAddressIPv4(IPList[i]).SubNetMask);
end;
end;
// show IP Addresses in the log file
if IPStrings.Count > 0 then
begin
for i := 0 to IPStrings.Count -1 do
WriteLog('DEBUG', 'IP Address #' + IntToStr(i) + ': ' + IPStrings[i]);
Result := IPStrings[0];
WriteLog('DEBUG', 'IP: ' + Result);
end else
WriteLog('DEBUG', 'IPStrings has no entries');
finally
IPStrings.Free;
end;
end else
WriteLog('DEBUG', 'TIdStackLocalAddressList has no entries');
finally
IPList.Free;
end;
except
On E: Exception do
begin
Result := '';
WriteLog('ERROR', 'IP Error: ' + E.message);
end;
end;
end;
将以上内容更改为
app.get('/register',(req,res,next)=>{
.....
.....
})
此外,我认为您不能通过简单地将端点称为localhost:3000 / register来直接从浏览器调用“ POST”端点。那将仅称为“ GET”端点。为了测试POST api,您必须创建一个表单并从中进行POST调用,或者使用工具/ google扩展程序(例如“ postman”)进行POST。
答案 2 :(得分:0)
A have a little bit mistake on your post api. you declare `app.get('/register',(req,res,next)` as **get** method but it must be **post**.
请复制片段轰鸣声并运行。谢谢
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const router = express.Router();
const bcrypt = require('bcrypt');
const saltRounds = 10;
// create connection to the database
const db = module.exports = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'pulse'
});
//connecting
db.connect((err) =>{
if(err){
throw err;
}
console.log('MySql connected...');
});
const app = module.exports = express();
app.use(bodyParser.urlencoded({extended: true})); //Accept URL Encoded params
app.use(bodyParser.json()); //accept JSON Params
//create user Table
app.get('/createUser',(req,res)=>{
let sql = 'CREATE TABLE users(id int AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), dateOfBirth VARCHAR(255), password VARCHAR(255), PRIMARY KEY(id))';
db.query(sql,(err,result)=>{
if(err) throw err;
console.log(result);
res.send('User table created');
});
});
//register user
app.post('/register',(req,res,next)=>{
const post_data = req.body;
const name = post_data.name;
const email = post_data.email;
const dateOfBirth = post_data.date;
const password = post_data.password;
let userEmail = {'email':email};
let sql = 'SELECT * FROM users WHERE ?';
let query = db.query(sql,userEmail, (err,result)=>{
if(err) throw err
//console.log('[MySQL ERROR',err);
if(result && result.length) {
res.json('User already exists');
}
else{
let insertUser = {'name':name, 'email':email, 'dateOfBirth':dateOfBirth, 'password':password};
let sql = 'INSERT INTO users SET ?';
let query = db.query(sql,insertUser,function(err,result){
if(err) throw err;
res.json('Registration successful');
});
}
});
});
//creating the server
app.listen('3000', () => {
console.log("Server started on port 3000");
});