有一个在Nodejs中实现的客户端。我将发送请求发送到Apache HTTP服务器,然后将该请求转发到后端服务器(它位于其他地方)。 所以我实现了Node js客户端和Apache模块。这两者之间的请求和响应都可以。现在我的问题是如何将此请求从Apache HTTP服务器转发到后端服务器。
Nodejs client.js
var request = require('request');
var userDetails={
username:"username",
password:"abc123"
}
var optsSingup = {
url: "http://localhost:80/a",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
form:{
username:userDetails.username,
password:userDetails.password,
}
};
request(optsSingup, function (err, res, body) {
console.log('error', err);
//console.log('status', res.statusCode);
console.log('body', body);
});
Apache模块(我一直在关注本教程http://httpd.apache.org/docs/2.4/developer/modguide.html示例 mod_example_config.c )。在这里,我将共享我的模块的处理程序部分。其他部分与 mod_example_config.c 相同。
typedef struct {
const char* key;
const char* value;
} keyValuePair;
static int example_handler(request_rec *r)
{
formData = readPost(r);
if (formData) {
int i;
for (i = 0; &formData[i]; i++) {
if (formData[i].key && formData[i].value) {
ap_rprintf(r, "%s = %s\n", formData[i].key, formData[i].value);
} else if (formData[i].key) {
ap_rprintf(r, "%s\n", formData[i].key);
} else if (formData[i].value) {
ap_rprintf(r, "= %s\n", formData[i].value);
} else {
break;
}
}
}
return OK;
}
keyValuePair* readPost(request_rec* r) {
apr_array_header_t *pairs = NULL;
apr_off_t len;
apr_size_t size;
int res;
int i = 0;
char *buffer;
keyValuePair* kvp;
res = ap_parse_form_data(r, NULL, &pairs, -1, HUGE_STRING_LEN);
if (res != OK || !pairs) return NULL;
kvp = apr_pcalloc(r->pool, sizeof(keyValuePair) * (pairs->nelts + 1));
while (pairs && !apr_is_empty_array(pairs)) {
ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
apr_brigade_length(pair->value, 1, &len);
size = (apr_size_t) len;
buffer = apr_palloc(r->pool, size + 1);
apr_brigade_flatten(pair->value, buffer, &size);
buffer[len] = 0;
kvp[i].key = apr_pstrdup(r->pool, pair->name);
kvp[i].value = buffer;
i++;
}
return kvp;
}