Java 发布到 nodeJS returns 404
Java posting to nodeJS returns 404
我正在尝试 post 从我的 java 代码到我的 nodeJS 应用程序的简单字符串。我启动服务器,当我在浏览器中访问它时,它会显示欢迎消息。
当我 运行 我的 java 代码到 post 到 localhost:8080/测试它 returns 一个 404 代码。我做错了什么?
express.js代码
var port = 8080;
const express = require('express');
const app = express();
app.get('', (req, res) => {
res.send('Hello express!')
})
app.get('/TEST', (req, res) => {
res.send('response send')
})
app.listen(port, () => {
console.log('Server is up on port '+port)
})
Java代码
public static void main(String[] args) throws Exception {
PostToNodejs pt = new PostToNodejs();
pt.post("http://localhost:8080/TEST", "Some data in string format");
}
public void post(String uri, String data) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.POST(HttpRequest.BodyPublishers.ofString(data))
.build();
HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(response.statusCode());
}
您没有在您的 Express 应用中为 /TEST 处理 post 方法。将方法从 get.
改为 post
app.post('/TEST', (req, res) => {
res.send('response send')
})
您只处理“/TEST”的 GET 路由,要修复您需要向快递代码添加 POST 路由的错误。您可以使用此代码:
app.post('/TEST', (request, response) => {
response.send("Post route working");
});
我正在尝试 post 从我的 java 代码到我的 nodeJS 应用程序的简单字符串。我启动服务器,当我在浏览器中访问它时,它会显示欢迎消息。
当我 运行 我的 java 代码到 post 到 localhost:8080/测试它 returns 一个 404 代码。我做错了什么?
express.js代码
var port = 8080;
const express = require('express');
const app = express();
app.get('', (req, res) => {
res.send('Hello express!')
})
app.get('/TEST', (req, res) => {
res.send('response send')
})
app.listen(port, () => {
console.log('Server is up on port '+port)
})
Java代码
public static void main(String[] args) throws Exception {
PostToNodejs pt = new PostToNodejs();
pt.post("http://localhost:8080/TEST", "Some data in string format");
}
public void post(String uri, String data) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.POST(HttpRequest.BodyPublishers.ofString(data))
.build();
HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(response.statusCode());
}
您没有在您的 Express 应用中为 /TEST 处理 post 方法。将方法从 get.
改为 postapp.post('/TEST', (req, res) => {
res.send('response send')
})
您只处理“/TEST”的 GET 路由,要修复您需要向快递代码添加 POST 路由的错误。您可以使用此代码:
app.post('/TEST', (request, response) => {
response.send("Post route working");
});