nodejs的express框架的response經常使用返回方式

經常使用的返回方式有四種html

  1. res.json()以json的形式返回數據java

  2. res.render(view [, locals] [, callback])返回對應的view和數據,相似於spring的modelandview,此方法能夠有回調函數,以處理可能出現的異常ajax

  3. res.send(body) 返回自定義的數據,好比json或者404等狀態spring

  4. res.redirect([status,] path) 這個方法其實不是返回,而是跳轉到另一個url上,相似於spring的redirectjson

首先仍是先說res.json
數組

官方文檔
Sends a JSON response. This method is identical to res.send() with an object or array 
as the parameter. However, you can use it to convert other values to JSON, 
such as null, and undefined. (although these are technically not valid JSON).

渣翻譯:能夠發送一個json響應,這個方法同res.send()同樣,一樣都是以一個對象或者數組做爲參數,你也能夠把其餘數據轉換成json而後發送,例如,null, undefined ,儘管這些值可能不是正確的json

官方例子瀏覽器

res.json(null)     
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })    //返回錯誤碼

若是你用ajax請求,能夠使用此方法作返回ide

第二種是res.sender()函數

這就是spring的modelandview啊oop

前面是返回對應的視圖名稱(不加文件後綴),後面就是要返回的數據

官方文檔
Renders a view and sends the rendered HTML string to the client. Optional parameters:

locals, an object whose properties define local variables for the view.

callback, a callback function. If provided, the method returns both 
the possible error and rendered string, but does not perform an automated response. 
When an error occurs, the method invokes next(err) internally.
渣翻譯: 把渲染視圖和html的字符串發送給客戶端瀏覽器,可選參數有
本地變量:發送到此本地變量對應的視圖的一個對象
回調函數:返回可能的錯誤和渲染字符串,但不執行自動響應。當發生錯誤時,該方法調用next(err)。

官方示例

// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

其中index是視圖的名稱,好比index.jade或者index.ejs等

不適用ajax,直接訪問此url,獲取返回值和模板,填充對應模板數據

第三個是res.send(),它能夠返回自定義的屬性

官方文檔
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, or an Array. 
渣翻譯:發送一個http響應
參數能夠是緩衝對象,字符串,對象,數則

官方示例

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

最後一個是res.redirect

舉例說,當你添加了一個帖子,返回一個帖子的id,而後又想直接打開帖子的內容,這個就有了用途,它會跳轉到對應的url上,就是重定向

官方文檔
Redirects to the URL dervied from the specified path, with specified HTTP status code status. 
If you don’t specify status, the status code defaults to 「302 「Found」.
渣翻譯:重定向到從指定的路徑的URL,與指定的HTTP狀態代碼狀態。若是不指定狀態,該狀態代碼默認爲302。

官方示例

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

這方法就是讓你去重定向的。

相關文章
相關標籤/搜索