![](/img/trans.png)
[英]Is there a way to run a Java Applet in node.js, at server side?
[英]How to POST to node.js from applet?
我有一个applet(不是我们的选择,它是MarioAI引擎),我想连接到使用express的node.js应用程序...但是我似乎无法让mongodb接受我发送的值在我通过本地主机的POST请求中。 我不断从节点获得200响应,但从猫鼬获得“未定义”响应,我怀疑这意味着我在Java中使用的URLEncoder正在处理通过某种方式发送的字符串。
我读到这个:
Java Applet连接我们的服务器以调用PHP文件时出现问题
并尝试使用Java进行以下OutputStreamWriter调用:
//EvaluateFrustration() takes an int but should come back with a float value
String frustrationString = Double.toString(EvaluateFrustration(this.periods));
try {
URL url = new URL("http://127.0.0.1:8888/mario");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
System.out.println(conn.getResponseCode());
conn.setUseCaches (false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter writer;
writer = AccessController
.doPrivileged(new PrivilegedExceptionAction<OutputStreamWriter>() {
public OutputStreamWriter run() throws IOException {
return new OutputStreamWriter(conn.getOutputStream());
}
});
String data = URLEncoder.encode("frustrationValueFirstRound="
+ frustrationString,"UTF-8");
writer.write(data);
writer.flush();
} catch (Exception e) {
}
在节点应用程序中(使用express和mongoose / mongodb),我写道:
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ExperimentSchema = new Schema({
experiment : ObjectId
, frustrationValueFirstRound : Number
});
mongoose.connect('mongodb://localhost/mariopaper');
mongoose.model('Experiment', ExperimentSchema);
var Experiment = mongoose.model('Experiment');
app.post('/mario', function(req, res){
var exp = new Experiment();
exp.frustrationValueFirstRound = req.body.frustrationValueFirstRound;
exp.save(function(err){ if (err) { throw err; }
res.send('ok');
});
作为参考,我想指出这个curl调用可以正常工作:
curl -d "frustrationValueFirstRound=99" http://localhost:8888/mario
任何人都知道我是否只是用Java错误地编写了POST消息,或者我在URLEncoder.encode()的工作方式中丢失了某些东西?
我认为那是因为您没有body-parser节点模块,即“在处理程序之前在中间件中解析传入的请求主体,可以在req.body属性下使用”。
尝试以下操作(在安装body-parser模块之后):
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ExperimentSchema = new Schema({
experiment : ObjectId
, frustrationValueFirstRound : Number
});
mongoose.connect('mongodb://localhost/mariopaper');
mongoose.model('Experiment', ExperimentSchema);
var Experiment = mongoose.model('Experiment');
app.post('/mario', function(req, res){
console.log(req.body); // Is there something here ?
var exp = new Experiment();
exp.frustrationValueFirstRound = req.body.frustrationValueFirstRound;
exp.save(function(err){ if (err) { throw err; }
res.send('ok');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.