简体   繁体   中英

Java posting to nodeJS returns 404

I am trying to post a simple string from my java code to my nodeJS application. I start the server and when i visit it in the browser it shows me the welcome message.

When i run my java code to post to localhost:8080/TEST it returns a 404 code. What am i doing wrong?

express.js code

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 code

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());
}

You don't handle the post method in your express app for /TEST. Change the method to post from get.

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

You are only handling the GET route for "/TEST", to fix the error you need to add a POST route to your express code. You can use this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM