gpt4 book ai didi

javascript - Node ,如何在 Node/express 应用程序上发送响应 header ?

转载 作者:行者123 更新时间:2023-12-03 06:25:26 25 4
gpt4 key购买 nike

我有一个基本的服务器。我需要通过的测试之一是发送 200 的响应 header 。我添加了服务器的代码,就像现在一样。但不确定如何发送响应 header 。感谢您提供的任何帮助!

var express = require('express');
var bodyParser = require('body-parser');
var Users = require('./models/users');

var app = express();
app.use(bodyParser.json());

// YOUR CODE BELOW
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var router = express.Router();

// middleware for all requests:
router.use(function(req, res, next){
console.log('we out here babay!');
// get to the next route and ensures we don't stop here.
next();
})

router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

app.use('/api', router);

// Do not touch this invocation of the `listen` method
app.listen('8888', function () {
console.log('listening on 8888');
});

// Do not touch the exports object
module.exports = app;

最佳答案

Use res.status(CODE) method!

res.status(200).json({ message: 'hooray! welcome to our api!' });

正如 jfriend00 的评论中所强调的那样,默认状态代码为 200,因此任何常规响应都将是 200,但对于 500404 等其他代码,如果您的客户端在读取响应时考虑它,您可以使用 res.status() 方法。

关于javascript - Node ,如何在 Node/express 应用程序上发送响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38678133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com