server
- package.json
{
"name": "node",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"axios": "^0.21.1",
"body-parser": "^1.19.0",
"cloudevents": "^4.0.3",
"express": "^4.17.1"
}
}
- app.js
const app = require("express")();
const { HTTP ,CloudEvent} = require("cloudevents");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({ limit: '50mb' }));
app.post("/", (req, res) => {
try {
const event = HTTP.toEvent({ headers: req.headers, body: req.body });
// respond as an event
const responseEventMessage = new CloudEvent({
source: '/',
type: 'event:response',
...event
});
responseEventMessage.data = {
hello: 'world'
};
console.log(event.toString())
res.status(201).json(responseEventMessage);
} catch (err) {
console.error(err);
res.status(415).header("Content-Type", "application/json").send(JSON.stringify(err));
}
});
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:${3000}`)
})
client
client.js
const axios = require("axios").default;
const { emitterFor, Mode, HTTP,CloudEvent } = require("cloudevents");
const type = "userlogin"
const source = "itmd_cust"
const subject = "demo"
const datacontenttype = "application/json"
const data = {
name:"dalongdemo",
age:333
}
const ce = new CloudEvent({ type, source, data:data ,datacontenttype,subject });
const message = HTTP.binary(ce); // Or HTTP.structured(ce)
console.log(message.headers)
function sendWithAxios(message) {
// Do what you need with the message headers
// and body in this function, then send the
// event
axios({
method: "post",
url: "http://localhost:3000",
data: message.body,
headers: message.headers,
});
}
const emit = emitterFor(sendWithAxios, { mode: Mode.BINARY });
emit(ce);
效果
- 运行
node app.js
node client.js