簡體   English   中英

404從本地托管服務器獲取請求時出錯

[英]404 Error with 'get' fetch request from locally hosted server

我正在使用在這里學到的原理(使用Express和MongoDB的CRUD應用程序)構建一個簡單的博客。 為了編輯以前發布的帖子,我想用一個博客文章的內容填充文本字段,該博客文章的標題是從下拉菜單中選擇的。 這樣,我可以輕松進行更改並提交。

我編寫了一個基本的“放置”獲取請求,該請求除了在出現問題時報告錯誤外,什么也不做:

fetch('articles', {method: 'put'})
        .then(  
            function(response) {  
                if (response.status !== 200) {  
                    console.log('Looks like there was a problem. Status Code: ' +  response.status);  
                    return;  
                }

                // Examine the text in the response  
                response.json().then(function(data) {  
                    console.log(data);  
                });  
            }  
        )  
        .catch(function(err) {  
            console.log('Fetch Error :-S', err);  
        });

這里沒有任何問題,因此執行console.log(data)

在此處輸入圖片說明

但是,當我將“ put”更改為“ get”(不進行其他更改)時,出現404錯誤:

在此處輸入圖片說明

'get'提取請求怎么會導致404錯誤,而'put'請求卻沒有呢? 我在本地托管此應用,因此我從localhost:3000運行它。 服務器代碼中的“獲取”,“發布”和“放置”操作如下所示:

app.get('/', function (req, res) {
    db.collection('articles').find().toArray(function (err, result) {
        if (err) return console.log(err);
        res.render('index.ejs', {articles: result});
    });
});

app.post('/articles', function (req, res) {
    db.collection('articles').save(req.body, function (err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
        res.redirect('/');
    });
});

app.put('/articles', function (req, res) {
    db.collection('articles')
    .findOneAndUpdate({title: 'test title'}, {
        $set: {
            title: req.body.title,
            body: req.body.body
        }
    }, {
        sort: {_id: -1},
        upsert: true
    }, function (err, result) {
        if (err) return res.send(err);
        res.send(result);
    });
});

我想消除此404錯誤,因此我可以繼續使用“獲取”請求的最終原因:使用先前發布的博客條目的內容填充文本字段。 完成修改后,我計划使用“ put”請求完成MongoDB中的更改。

請讓我知道您是否需要任何其他信息。 非常感謝您的建議!

您沒有GET /articles路線; 您確實有一個GET /路線。

如果要使GET /articles工作,則應將第一個參數app.get'/articles'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM