Java发送到nodeJS返回404



我正试图从我的java代码发布一个简单的字符串到我的nodeJS应用程序。我启动服务器,当我在浏览器中访问它时,它会显示欢迎消息。

当我运行我的java代码张贴到localhost:8080/TEST它返回一个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());
}

你不处理post方法在你的express应用程序/TEST。

app.post('/TEST', (req, res) => {
res.send('response send')
})

您只处理了"/TEST"的GET路由,要修复这个错误,您需要在express代码中添加POST路由。您可以使用以下代码:

app.post('/TEST', (request, response) => {
response.send("Post route working");
});

最新更新