تم إعداد ترجمة المقال استعدادًا لبدء دورة مطوري Node.js
Koa هو إطار عمل صغير يسمح لك بإنشاء تطبيقات خلفية تعمل على Node.js
.
في هذه المقالة ، سننظر في كيفية إرسال أنواع مختلفة من الردود باستخدام Koa.
إيفاد الجسم
يمكنك تعيين سمة النص لإرسال نص الاستجابة ctx
. على سبيل المثال ، يمكننا إرسال نص الرد كما يلي:
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.body = 'foo';
});
app.listen(3000);
في الكود أعلاه ، نقوم بتعيين الخاصية ctx.body
على "foo". إذن هذا ما نحصل عليه عندما نذهب إلى العنوان /
باستخدام متصفحنا أو نطلبه باستخدام عميل HTTP.
رأس لإرسال الرد
يمكننا إرسال ردود في كود Koa الخاص بنا عن طريق تعيين الخاصية ctx.response
. لتعيين الرأس ، يمكننا تعيين رأس الاستجابة باستخدام ctx.set
. على سبيل المثال ، يمكننا استخدامه على النحو التالي:
const app = new Koa();
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
ctx.body = 'hello';
});
app.listen(3000);
في الكود أعلاه ، ندعو ctx.set
إلى تثبيت عناوين مختلفة ، بما في ذلك العنوان: Access-Control-Allow-Origin
، Access-Control-Allow-Headers
و Access-Control-Allow-Methods
.
/
, HTTP , Chrome Postman.
, respondbse.status
.
, :
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.status = 202;
ctx.body = 'accepted';
});
app.listen(3000);
ctx.status 's 202. , / , 202 .
, , :
200 - OK
201 - created -
202 - accepted -
203 - non-authoritative information-
204 - no content-
301 - moved permanently -
302 - found -
303 - see other - .
307 - temporary redirect -
308 - permanent redirect -
400 - bad request -
401 - unauthorized -
403 - forbidden-
404 - not found -
405 - method not allowed-
406 - not acceptable-
422 - unprocessable entity -
500 - internal server error-
501 - not implemented-
502 - bad gateway-
504 - gateway timeout-
(Headers)
ctx.response.lastModified
.
, :
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.response.lastModified = new Date(2020, 0, 1);
ctx.body = 'foo';
});
app.listen(3000);
lastModified
1 2020 , , /
, Last-Modified
Wed, 01 2020 00:00:00 GMT
.
Content-Type, ctx.type
. , :
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.type = 'text/plain; charset=utf-8';
ctx.body = 'foo';
});
app.listen(3000);
:
ctx.type = 'text/plain; charset=utf-8';
Content-Type 'text/plain; charset=utf-8'
. Content-Type /
.
, ctx.append()
. 2 .
, :
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.append('a', 1);
ctx.body = 'foo';
});
app.listen(3000);
ctx.append()
'a'
1.
, /
, A 1.
, ctx.append()
. , ctx.body
.
, ctx.status
.