JSON API with ExpressJS
suggest changevar express = require('express');
var cors = require('cors'); // Allow cross-origin requests
var app = express();
app.use(cors()); // for all routes
var port = process.env.PORT || 8080;
app.get('/', function(req, res) {
var info = {
'string_value': 'StackOverflow',
'number_value': 8476
}
res.json(info);
// res.send(JSON.stringify(info)) sends the same bytes, but the
// Content-Type is not application/json. res.json sets that header.
//you can add a status code to the json response
/* res.status(200).json(info) */
})
app.listen(port, function() {
console.log('Node.js listening on port ' + port)
})
On http://localhost:8080/ output object
{
"string_value": "StackOverflow",
"number_value": 8476
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents