简体   繁体   English

node.js:我的 RESTAPI 中的 POST 方法不起作用

[英]node.js: The POST method in my RESTAPI does not work

I start learning Node.js and Express.js and I'm trying to create a simple API to list data from JSON file (using the GET method) and add a new user using the POST method.我开始学习 Node.js 和 Express.js,我正在尝试创建一个简单的 API 来列出 JSON 文件中的数据(使用 GET 方法)并使用 POST 方法添加新用户。

the GET method works fine but the POST method does not work GET 方法工作正常,但 POST 方法不起作用

when I request http://127.0.0.1:8080/listusers the API sends all users in a JSON file.当我请求http://127.0.0.1:8080/listusers时,API 将所有用户发送到 JSON 文件中。 when I request http://127.0.0.1:8080/adduser the API has to add new User Info and send the new data back to the browser.当我请求http://127.0.0.1:8080/adduser时,API 必须添加新的用户信息并将新数据发送回浏览器。

NOTE: I read all the questions on Stackoverflow about this problem but non of them help me so I have to ask again.注意:我在 Stackoverflow 上阅读了有关此问题的所有问题,但没有一个对我有帮助,所以我不得不再次提问。

the problem is when I request http://127.0.0.1:8080/adduser I get the following error问题是当我请求http://127.0.0.1:8080/adduser时出现以下错误

Cannot GET /adduser

here is the server.js :这是server.js

var express = require('express');
var app = express();
var fs = require('fs');

var user = {
        "user4" : {
               "name" : "mounir",
       "password" : "password4",
       "profession" : "teacher",
       "id": 4
    }
};

app.post('/adduser', function (req, res) {
        // First read existing users.
        fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
               data = JSON.parse( data );
               data["user4"] = user["user4"];
               console.log( data );
       res.end(JSON.stringify(data) );
    });
});

app.get('/listusers', function (req, res) {
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        console.log(data);
        res.end(data);
    });
});

var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("listening at http://%s:%s", "0.0.0.0", port)
});

The answer is in the error.答案在错误中。 Cannot GET /adduser.无法获取 /adduser。 Keyword GET!关键字获取! If you are making a post request, be sure you include the appropriate headers and that you are making a POST request, with a body, and not a GET request.如果您正在发出 post 请求,请确保包含适当的标头,并且您正在发出 POST 请求,带有正文,而不是 GET 请求。 For instance if you are using fetch:例如,如果您使用 fetch:

 const myInit = { method: 'POST', headers: myHeaders, body: { ... } }; fetch("http://127.0.0.1:8080/adduser", myInit) .then(res => { ... });

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

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