ntex-rs / examples

Apache License 2.0
86 stars 19 forks source link

Example for returning a list of objects as JSON #5

Closed vasily-kartashov closed 3 years ago

vasily-kartashov commented 3 years ago

Is there an example of what would be the NTEX equivalent of the following express.js code:

app.get('/names', (req, res) => {
    names = ['John', 'Jack', 'James'];
    res.setHeader('Content-Type', 'application/json')
    res.send(JSON.stringify(names))
})
fafhrd91 commented 3 years ago

if you need client then https://docs.rs/ntex/0.3.8/ntex/http/client/struct.ClientRequest.html#method.send_json

if you need server handling then https://github.com/ntex-rs/examples/blob/6b8bb1160bdec940b8e4ec61fbc56b84466c6a48/json/src/main.rs#L14

vasily-kartashov commented 3 years ago

@fafhrd91 Thanks for the quick reply. Is this the recommended way:

async fn names()  -> HttpResponse {
    let names: Vec<&str> = vec!["John", "Jack", "James"];
    let body = ntex::web::types::Json(names);
    HttpResponse::Ok().json(&body.0)
}
fafhrd91 commented 3 years ago

HttpResponse::Ok().json(names) should just work