javascript - 发送 JSON 到不同的地址然后 res
问题描述
我创建了一个小型快递模块。这个 atm 监听url
在 localhost 上运行,但计划监听triggerURL:ListenPort
并从外部服务运行。
clientA:服务器应接收来自网页(triggerURL
)的调用,并作为响应将JSON
对象发送到unity_url
。
clientB:一个统一的应用程序将打开正在收听SendingPort
。
问题是,虽然我将 JSON 发送到 res 并返回到 clientA 没有问题,但我不确定如何创建一个新的可写流并将 json 发送到 clientB 使用resp
and writable
。
var express = require('express');
var fs = require('fs');
var app = express();
var triggerURL = ''; //i'll send an http request to this adress to trigger the action from server
var JSON = {
item: "seeds",
Answers: "5",
richText: "<b>How can you reduce crop toxicity by turning plants upside down?</b><br/>Idea:<br/> Upside-down gardening is a hanging vegetable garden being the suspension of soil and seedlings of a kitchen garden to stop <b>pests</b> and blight,and eliminate the typical gardening tasks of tilling, weeding, and staking plants."
}
var port = process.env.PORT || 3000;
var ListenPort = '8086'; // my port to recieve triggers
var SendingPort = '4046'; // which unity will listen to
var unity_url ='185.158.123.54:'+SendingPort; //fake IP, just for the example
//triggerURL
app.get('/', function(req,res){
var resp = JSON.stringify(JSON);
var writable = fs.createWriteStream();
//res.json(JSON); //instead i wanna send it to unity_url;
});
//app.listen(ListenPort);
app.listen(port);
解决方案
您需要向目标网址发送请求。例如(使用node-fetch
)。
const fetch = require('node-fetch');
const express = require('express');
const app = express();
var JSON = {
item: "seeds",
Answers: "5",
richText: "<b>How can you reduce crop toxicity by turning plants upside down?</b><br/>Idea:<br/> Upside-down gardening is a hanging vegetable garden being the suspension of soil and seedlings of a kitchen garden to stop <b>pests</b> and blight,and eliminate the typical gardening tasks of tilling, weeding, and staking plants."
}
const port = process.env.PORT || 3000;
const unity_url ='185.158.123.54:4046'; //fake IP, just for the example
//triggerURL
app.get('/', function(req,res){
var resp = JSON.stringify(JSON);
fetch(unity_url, {
method: 'post',
body: resp,
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(data => console.log(data));
res.status(200).send('OK');
});
app.listen(port);
推荐阅读
- r - 在 R 中使用“”
- java - 具有货币值动态掩码的文本字段 JavaFX(使用 TextFormatter)
- python-3.x - Git分支不显示任何结果
- php - 如何使用 php 从 MySQL 表中不同列的相同值中获取一个?
- javascript - 错误 instanceof X 没有按预期工作
- docker - 无法使用 Windows Docker 桌面上的 Kubernetes 连接到 NodePort 上的服务
- javascript - 使用 .load 从另一个页面加载内容会弄乱我当前的 css
- msal-react - 为非水疗应用程序实施 msal-react?
- assembly - 为什么 clang 为 64 位 double 的绝对值发出 32 位 float ps 指令?
- javascript - 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端 Express EJS NODE 后无法设置标头