gpt4 book ai didi

javascript - POST JSON 到 Node.JS ,语法错误 : Unexpected token %

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

我想通过 Node.JS POST API 将 JSON 对象 POST 到 Mongodb,无法上传除 Node.js 始终打印之外的任何内容,

SyntaxError: Unexpected token %

如果我删除 Android 端:

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

可以上传到数据库,但变成了未定义

{"{\"artist\":\"U\",\"weeksAtOne\":\"000000\",\"decade\":\"Hhhhh\",......

这是 Android JSON 对象在 Debug模式下的样子

jsonObject = {JSONObject@18572} "{"artist":"Fffffff","weeksAtOne":"Ppp","decade":"Kkkkk","song":"888","__v":0}"

它没有 token “%”,但是node.js总是打印这个,请帮忙,卡在这里一整天

安卓代码

  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);

路由.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]);
}
});
});
}

最佳答案

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

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

第一行似乎完美地完成了需要完成的工作,因此删除第二行。

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

关于javascript - POST JSON 到 Node.JS ,语法错误 : Unexpected token %,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525125/

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