简体   繁体   English

Express node.js api app.post 适用于 / 但不适用于 /path

[英]Express node.js api app.post does work for / but not with /path

I am new at Node.js and trying to make an API that will do CRUD operations in sql server.我是 Node.js 的新手,并试图制作一个 API,它将在 sql 服务器中执行 CRUD 操作。 The problem for me is that I can get the data but cannot post it, and get the error "cant get /".对我来说,问题是我可以获取数据但无法发布它,并得到错误“无法获取 /”。 I know there are similar questions about this subject but nothing works for me so I thought maybe my code has different kinds of error.我知道关于这个主题有类似的问题,但对我没有任何作用,所以我想我的代码可能有不同类型的错误。 Any help will be appreciated and save my life in a way.任何帮助将不胜感激,并以某种方式挽救我的生命。 Also, this is my first question on stackoverflow, sorry for the possible mistakes..另外,这是我关于stackoverflow的第一个问题,对可能出现的错误深表歉意..

Here is the server.js这是server.js

 const sql = require('mssql'); const express = require('express'); const bodyParser = require('body-parser'); var port = process.env.port || 5000; const sqlConfig = require('./connection/connect') const app = express(); app.use(express.json()); // json desteklemesi için app.use(express.urlencoded({ extended: true })); app.get("/test", (req, res, next) => { new sql.ConnectionPool(sqlConfig).connect().then(pool => { return pool.query('select * from tblProfile') }).then(result => { res.send(result); }) }) app.post('/test', (req, res) => { let name = req.query.name; let lastname = req.query.lastname; let email = req.query.email; let password = req.query.password; let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)"; conn.query(sql, [name, lastname, email, password], (err, result) => { if (err) throw err; res.write("inserted."); res.end(); }); app.listen(port, () => { console.log("working: " + port) }) });

This is the connect.js这是connect.js

 var sqlConfig = { server: '192.168.1.2', database: 'profile', user: 'username', password: 'user', }; module.exports = sqlConfig;

This is happening because you aren't responding or sending anything to that route发生这种情况是因为您没有响应或向该路由发送任何内容

So if you want to get rid of the error Run所以如果你想摆脱错误 Run

app.get('/', (req,res)=>{
   res.send('hello world')
}

But if you want to send a static file to the route Create a folder call public * note it can be anything但是如果你想发送一个 static 文件到路由创建一个文件夹调用 public *注意它可以是任何东西

And type并输入

var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

Then you can access code in the dir然后您可以访问目录中的代码

And as for the writing I think you should try this至于写作,我认为你应该试试这个

app.post('/test', (req, res) => {
    let name = req.body.name;
    let lastname = req.body.lastname;
    let email = req.body.email;
    let password = req.body.password;
    let sql = "INSERT INTO tblProfile(name,lastname,email,password VAUES(? ? ? ?)";
    conn.query(sql, [name, lastname, email, password], (err, result) => {
        if (err) throw err;
        res.write("inserted.");
        res.end();
    });

Change query to body Since you installed body-parser将查询更改为 body 因为您安装了 body-parser

Taking a quick look over your code, the only issues I can see are in your query to submit the data.快速查看您的代码,我能看到的唯一问题是您提交数据的查询。 Within your query statement, I added a closed parentheses after the variables to be entered into the database and made a typo correction to the word Values.在您的查询语句中,我在要输入数据库的变量后添加了一个右括号,并对单词 Values 进行了错字更正。 I also changed up how the data is retrieved from req.query to destructure it and simply the code a bit.我还更改了从 req.query 中检索数据的方式,以对其进行解构,并简化代码。 Based on everything else I saw, and the fact that you are able to get data from the database, this should work out fine.根据我看到的所有其他内容,以及您能够从数据库中获取数据的事实,这应该可以正常工作。 If it doesn't, I would recommend inserting some console.log() statements in the post query to see where it might be having issues and why.如果没有,我建议在 post 查询中插入一些console.log()语句,以查看可能出现问题的位置以及原因。 For example, you could run console.dir(req.query);例如,您可以运行console.dir(req.query); in your post route to see what data is actually coming from the req and make sure it is all there.在您的发布路线中查看实际来自 req 的数据并确保它们都在那里。 If something is missing, then the query won't actually execute.如果缺少某些内容,则查询将不会实际执行。 If this doesn't work, let me know, along with the information from any console logs you did and I'll take another look at it.如果这不起作用,请告诉我,以及您所做的任何控制台日志中的信息,我会再看一下。

 const sql = require('mssql'); const express = require('express'); const bodyParser = require('body-parser'); var port = process.env.port || 5000; const sqlConfig = require('./connection/connect') const app = express(); app.use(express.json()); // json desteklemesi için app.use(express.urlencoded({ extended: true })); app.get("/test", (req, res, next) => { new sql.ConnectionPool(sqlConfig).connect().then(pool => { return pool.query('select * from tblProfile') }).then(result => { res.send(result); }) }) app.post('/test', (req, res) => { //console.dir(req.query); let {name, lastname, email, password} = req.query; let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)"; conn.query(sql, [name, lastname, email, password], (err, result) => { if (err) throw err; res.write("inserted."); res.end(); }); app.listen(port, () => { console.log("working: " + port) }) });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM