节点Js撤消完整HTTP页面而不是JSON数据

时间:2015-04-20 19:39:05

标签: ios json node.js afnetworking-2

我有一个客户端ios应用程序,它使用afnetworking2连接到Node.Js后端,该后端应该使用来自后期路由的json数据进行响应。在localhost上测试时一切都很好但是当我在heroku上实时部署时,应用程序会发送索引页面的整个html而不是json。我不确定如何解决这个问题,甚至不知道为什么要开始发送html。任何和所有的帮助表示赞赏。我喜欢stackoverflow社区!我的代码如下:

app.js:

var express = require('express'),
routes = require('./routes/index'),
api = require('./routes/api'),
mobiTokenAuth = require('./routes/jwt'),
https = require('https'),
cons = require('consolidate'),
mustac = require('mustache'),
path = require('path'),
bodyParser  = require('body-parser'),
nodemailer = require("nodemailer"),
templatesDir = path.resolve(__dirname + '/templates'),
emailTemplates = require('email-templates'),
mysql = require('mysql2');
morgan = require('morgan');

var app = module.exports = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.engine('html', cons.mustache);
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({
 extended: true}));
app.use(bodyParser.json());
app.use(morgan('combined'));

// Set content type GLOBALLY for any response.
app.use(function (req, res, next) {
 res.contentType('application/json');
 next();
});

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST', 'PUT', 'DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');    
  next();
});

app.disable('x-powered-by');    

app.get("/", function(req, res){
 res.render('index');  
});
app.get("/partials/:name", routes.partials);
var port = process.env.PORT || 3000;
 app.listen(port, function(req, res) {
 console.log("Listening on " + port);
});

app.post('/api/signup', function(req, res){
 console.log(req);

 res.contentType('application/json');

 var data = {
  json: "test to see if data variable goes through as json data"
 } 
 res.json({data:data});
 next();
});

目前返回:

<html lang="en" ng-app="myApp">
 <head>
 <base href='/'>
 <body><div>Testing to see if html data is sent instead of json</div></body>
</html>

1 个答案:

答案 0 :(得分:1)

app.post('/api/signup', function(req, res){
 console.log(req);

 res.contentType('application/json');

 var data = {
  json: "test to see if data variable goes through as json data"
 } 
 res.json({data:data});
 next();
});

有两个错误,接下来没有定义,然后在你回复后调用next。

你也不需要使用res.contentType('application/json');做一个res.json()来处理标题。

相关问题