我是Node.js的新手,我正在关注this tutorial。一切都很好,除非我尝试返回一个json对象,如下所示:
router.get('/', function(req, res) {
res.send({
users: ["Will", "Laura2"]
});
});
浏览器将“users”对象显示为“文档”类型,而不是application / json类型。任何类型(状态代码,文本/普通等)都会出现相同的情况。
我的其余代码与教程中的代码完全相同。
├── body-parser@1.13.3
├── cookie-parser@1.3.5
├── debug@2.2.0
├── express@4.13.3
├── hjs@0.0.6
├── less-middleware@1.0.4
├── morgan@1.6.1
└── serve-favicon@2.3.0
npm 2.14.7
node v4.2.2
编辑:这是我的app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
编辑:这是我的index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
//router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
//});
router.get('/', function(req, res) {
res.send({
users: ["Will", "Laura"]
});
});
module.exports = router;
我做错了什么?
编辑:
看起来“application / json”类型未被接受,因此浏览器将内容显示为“文档”类型。见下图:
答案 0 :(得分:0)
router.get('/', function(req, res) {
res.json({
users: ["Will", "Laura2"]
});
});
只需将'send'替换为'json'就可以了...... 而且,对于返回状态代码,您可以在下面使用...
router.get('/', function(req, res) {
res.status(200).json({
users: ["Will", "Laura2"]
});
});