2017-08-23 43 views
1

我在Atom中使用服務器JavaScript文件,JSON數據和節點服務器進行編程!JSON網址無法捕獲空錯誤

var fs = require('fs'); 
var dataP = fs.readFileSync('database.json'); 
var data = JSON.parse(dataP); 
var express = require('express'); 
var app = express(); 
var server = app.listen(3000); 

app.use(express('website')); 
app.get('/check/:input', addInput); 

function addInput(request, response){ 
var inputData = request.params.input; 
if(!inputData){ 
      response.send("Error: no input was found"); 
     } 
} 

所以,我必須進入nodemon server.js當我測試的URL代碼@本地主機上運行我的服務器端:3000 /檢查也不會趕上我寫錯誤的錯誤消息:沒有發現輸入,我發現這很奇怪,因爲如果我假設正確,它是空輸入。我也嘗試更改if語句並添加:

if(!data && data == null) 

//Also tried 

if(!data || data == null) 

這些語句都不能捕獲錯誤。我在從服務器返回得到的消息是:無法獲得/檢查/

//if I add a ? at the end of input like this 

app.get('/check/:input?'); 

我會得到一個消息:內部服務器錯誤

會不會有另一種解決方案來處理捕獲錯誤?我試圖調試這個,但它會跳過app.get行,我然後無法觀察要檢查的變量。

+0

[Express js可選參數]的可能重複(https://stackoverflow.com/questions/41284193/express-js-optional-parameter) – styfle

+0

@styfle不一樣,我試過在星號前添加一個星號?所以它會** app.get(/ check /:input *?); **仍然是一樣的東西,沒有結果 – Zulu

+0

你試過'app.get('/ check /:input *')'嗎? – styfle

回答

0

我在文檔中找不到它,但經過多次嘗試後,我能夠使用路徑/check/:input*?(注意星號和問號)使其工作。

這裏是我的代碼:

const express = require('express'); 
const app = express(); 
const server = app.listen(3000); 

app.use(express('website')); 

app.get('/check/:input*?', (req, res) => { 
    const { input } = req.params; 
    if (!input) { 
     res.send('Value not specified!'); 
    } else { 
     res.send(`Value was "${input}", woohoo!`); 
    } 
}); 
  • 參觀/check打印Value was not specified
  • 在新參觀/check/winning打印Value was "winning", woohoo!

我與節點8.4.0的測試,並表示4.15.4項目。據我所知,上面的代碼應該在節點6.7+中工作,並且表達爲4.0+。

請參閱this answer它解決了同樣的問題。

相關問題