I'm very new to node and trying to set up a simple backend solution to handle the routes in my Backbone application. Right now I'm routing everything to index.html. My problem is when I make a data request the response es back with Content-Type:text/html; charset=UTF-8
when I need it to be Content-Type:application/json
. I know I need to set this header somewhere but not sure where and was wondering if someone could help?
JS
var express = require('express');
var port = 8000;
var server = express();
server.use('/dist', express.static(__dirname + '/dist'));
server.get('scripts/data/*.json', function(req, res) {
return res.json({
success: true
})
});
server.get('*', function(req, res){
return res.sendFile(__dirname + '/index.html');
});
server.listen(port, function() {
console.log('server listening on port ' + port);
});
I'm very new to node and trying to set up a simple backend solution to handle the routes in my Backbone application. Right now I'm routing everything to index.html. My problem is when I make a data request the response es back with Content-Type:text/html; charset=UTF-8
when I need it to be Content-Type:application/json
. I know I need to set this header somewhere but not sure where and was wondering if someone could help?
JS
var express = require('express');
var port = 8000;
var server = express();
server.use('/dist', express.static(__dirname + '/dist'));
server.get('scripts/data/*.json', function(req, res) {
return res.json({
success: true
})
});
server.get('*', function(req, res){
return res.sendFile(__dirname + '/index.html');
});
server.listen(port, function() {
console.log('server listening on port ' + port);
});
Share
edited Oct 1, 2015 at 11:49
styler
asked Oct 1, 2015 at 9:28
stylerstyler
16.5k25 gold badges85 silver badges139 bronze badges
2 Answers
Reset to default 3You need to do it in get method
add
res.setHeader("Content-Type", "application/json");
before sendFile
https://nodejs/api/http.html#http_response_setheader_name_value
You can also use middleware:
In express you can use express.static(root, [options])
Where one of option can be: setHeaders
function
Check these links:
- Send additional http headers with Express.JS
- http://expressjs./api.html
- http://expressjs./starter/static-files.html
Here's another approach.
As pointed out in the answer above, you can pass additional parameters to express.static
.
So, in order to serve your *.json
files you should put this code about your *
route:
app.use('/scripts', express.static(__dirname + '/scripts'), {
setHeaders: function(res) {
res.setHeader("Content-Type", "application/json");
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745057973a4608786.html
评论列表(0条)