Express.js – res.jsonp() 方法


res.jsonp() 方法傳送了帶有 JSONP 支援的 json 響應。此方法類似於 res.json() 方法,唯一的區別在於它提供了 JSONP 回撥支援。

語法

res.jsonp ( [body] )

例子 1

使用 res.jsonp() 方法:

// res.jsonp([body]) Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function(req, res){
   res.jsonp({ title: 'Welcome to Tutorials Point !' });
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

C:\home
ode>> node resJsonp.js Server listening on PORT 3000

使用 GET 請求,訪問以下終結點:https://:3000/api

{"title":"Welcome to Tutorials Point !"}

例子 2

我們來看另一個例子。

// res.jsonp([body]) Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
// With the next() middleware
app.use('/api', function(req, res, next) {
   res.jsonp({ name: 'Parent Method' });
   next();
})

app.get('/api', function(req, res) {
   res.end();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

C:\home
ode>> node resJsonp.js Server listening on PORT 3000

使用 GET 請求訪問以下終結點 – https://:3000/api

{"name":"Parent Method"}

更新於:28-Mar-2022

467 個瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.