POST JSON到Node.JS,SyntaxError:意外的标记%

时间:2016-02-20 15:17:23

标签: javascript android json node.js mongodb

我想通过Node.JS POST API将JSON对象POST到Mongodb,无法上传除node.js以外的所有内容,

  

SyntaxError:意外的标记%

如果我删除了android端:

  

Connection.setRequestProperty(" Content-Type"," application / json");

它可以上传到DB但是变成了未定义的

  

{" {\"艺术家\":\" U \" \" weeksAtOne \":\" 000000 \" \"十年\":\" HHHHH \",......

这是android JSON对象在调试模式下的样子

  

jsonObject = {JSONObject @ 18572}   " {"艺术家":" FFFFFFF"" weeksAtOne":"了ppp""十年&#34 ;: " KKKKK""曲":" 888"" __ v":0}"

它没有令牌"%",但node.js总是打印出来,请帮忙,坚持到这一整天

android代码

  StringBuilder sb = new StringBuilder();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("artist", artist.getText().toString());
                jsonObject.put("weeksAtOne", week.getText().toString());
                jsonObject.put("decade", year.getText().toString());
                jsonObject.put("song", song.getText().toString());
                jsonObject.put("__v",0);

                String http = "http://36.224.137.68:3000/songs";
                URL url = new URL(http);
                Connection = (HttpURLConnection) url.openConnection();
                Connection.setDoOutput(true);
                Connection.setRequestMethod("POST");
                Connection.setUseCaches(false);
                Connection.setConnectTimeout(10000);
                Connection.setReadTimeout(10000);
                Connection.setRequestProperty("Content-Type", "application/json");
                Connection.setRequestProperty("Host", "36.224.137.68:3000/songs");
                Connection.connect();
                OutputStreamWriter out = new OutputStreamWriter(Connection.getOutputStream());
                out.write(jsonObject.toString());
                out.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
                out.flush();
                out.close();
                int HttpResult = 0;
                try {
                HttpResult = Connection.getResponseCode();
                }catch (IOException ioex){
                    Log.v("ConnError", ioex.getMessage());
                };
                if (HttpResult == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            Connection.getInputStream(), "utf-8"));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();

                    System.out.println("" + sb.toString());

                } else {
                    System.out.println(Connection.getResponseMessage());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();

            } catch (IOException e) {
               e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }finally{
                if(Connection!=null)
                    Connection.disconnect();
            }


        }
    });

}
}

NodeJS:app.js代码

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
var jsonParser = bodyParser.json();


app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});


app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.post('/songs',songs.addSong);

route.js

var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri =         "mongodb://xxxxxxxx:xxxxxxxx@ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;

var body = require('body-parser');

db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});

exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
  res.send(items);
});
});
};

exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
{ if (err) {
throw err;
} else
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
  res.send(item);
});
});
};

exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
  if (err) {
    res.send({'error':'An error has occurred'});
  } else {
    console.log('Success: ' + JSON.stringify(result[0]));
    res.send(result[0]);
  }
});
});
}

1 个答案:

答案 0 :(得分:1)

在这两行中输出两次JSON字符串:

out.write(jsonObject.toString());
out.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));

第一行似乎完成了需要做的事情,所以删除第二行。

虽然这种重复本身已经导致无效的JSON,但是发布的URL编码数据也没有任何意义,并且确实可以引入您遇到的%个字符。