搜索

首页  >  问答  >  正文

javascript - 为什么express,get的res.sendFile返回的是html纯文本?

let express = require('express');
let db = require('./db/db');
let app = express();

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

let apiRoutes = express.Router();

apiRoutes.get('/seller', function (req, res) {
  db.find(req.query.id, function (err, result) {
    if (err) {
      console.log('Error:' + err);
      return;
    } else {
      let seller = result[0].toObject();
      delete seller.goods;
      delete seller.ratings;

      res.json({
        errno: 0,
        data: seller
      });
    }
  });
});

apiRoutes.get('/goods', function (req, res) {
  db.find(req.query.id, function (err, result) {
    if (err) {
      console.log('Error:' + err);
      return;
    } else {
      res.json({
        errno: 0,
        data: result[0].toObject().goods
      });
    }
  });
});

apiRoutes.get('/ratings', function (req, res) {
  db.find(req.query.id, function (err, result) {
    if (err) {
      console.log('Error:' + err);
      return;
    } else {
      res.json({
        errno: 0,
        data: result[0].toObject().ratings
      });
    }
  });
});

app.use('/api', apiRoutes);

app.listen(3000);
console.log('Listening on port 3000...');

为什么


app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

返回的是html纯文本而不是文件?

但是

var express = require('express');
var bodyParser = require('body-parser');
var db = require('./validate');

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));

// respond with "hello world" when a GET request is made to the homepage
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.post('/dosomething', (req, res) => {
    var message = req.body;
    db.create(message.name, message.age, message.city, function (err, mes) {
        if (err) {
            throw err;
        } else {
            console.log(mes);
        }
    });
})

app.listen(1212);
console.log('is ok ...');

就能正常显示网页?

PHP中文网PHP中文网2750 天前934

全部回复(2)我来回复

  • 淡淡烟草味

    淡淡烟草味2017-05-17 09:58:57

    第一个你设置了header
    res.header("Content-Type", "application/json;charset=utf-8");
    浏览器就会按照json解析

    第二个,没设置,默认就是
    Content-Type:text/html; charset=utf-8
    自然就按照 html解析

    回复
    0
  • PHPz

    PHPz2017-05-17 09:58:57

    对头,设置Content-Type,你用Chrome浏览器看看http响应的header对不对。

    回复
    0
  • 取消回复