Express:由于接受:无法访问浏览器的路由:application / javascript header missing

时间:2018-03-25 15:42:58

标签: express webpack

我是新来表达的。我有一个在快递上运行的Vue应用程序。我有一些API路由,我可以通过浏览器使用axios访问。要使用邮递员访问这些路线,我必须有标题:

accept: application/javascript

它返回实际API的结果。如果我不使用此标头,我会从webpack获取生成的index.html。我需要重用这些路由之一,根据参数返回excel / pdf,并通过页面上的链接访问它。

这是我的server.js - 基于https://github.com/southerncross/vue-express-dev-boilerplate



import express from 'express'
import path from 'path'
import favicon from 'serve-favicon'
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import webpack from 'webpack'

const argon2 = require('argon2');
const passport = require('passport')
const LocalStrategy = require ('passport-local')
const session = require('express-session')


import history from 'connect-history-api-fallback'

// Formal(Prod) environment, the following two modules do not need to be introduced
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'

import config from '../../build/webpack.dev.conf'

const app = express()
app.set('trust proxy', true)

app.set("view engine", "pug")
app.set('views', path.join(__dirname, 'views'))

app.use ('/', require('./routes'))


app.use(session({
	secret: process.env.SESSION_SECRET || 'secretsauce',
	resave: false,
	saveUninitialized: true
}))


app.use(history())
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
	extended: false
}))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

const compiler = webpack(config)

app.use(webpackDevMiddleware(compiler, {
	publicPath: config.output.publicPath,
	stats: {
		colors: true
	}
}))

app.use(webpackHotMiddleware(compiler))



////////// PASSPORT ///////////////////////
app.use (passport.initialize ());
app.use (passport.session ());

async function authenticateUser (username, password) {
//...
		
}

passport.use (
	new	LocalStrategy (async (username, password, done) => {
		const user = await authenticateUser (username, password)
		if (!user) {
			return done (null, false, {
				message: 'Username and password combination is wrong',
			});
		}

		delete user.password;
		return done (null, user)
	})
);

// Serialize user in session
passport.serializeUser ((user, done) => {
	done (null, user);
});

passport.deserializeUser (function(user, done) {
	if(user === undefined || !user || Object.keys(user).length === 0)
		return done(null, false)
	else
		done (null, user);
});

//////////// passport end ///////////////


app.set("view engine", "pug")
app.use(express.static(path.join(__dirname, 'views')))
app.get('/', function (req, res) {
	res.sendFile('./views/index.html')
})
app.get('/success', function (req, res) {
	res.render('./views/success')
})



app.use ('/api', require('./api'))


// catch 404 and forward to error handler
app.use(function (req, res, next) {
	var err = new Error('Not Found')
	err.status = 404
	next(err)
})

app.use(function (err, req, res) {
	res.status(err.status || 500)
	res.send(err.message)
})




let server = app.listen(80)

export default app




这里有点 api.js



const {Router} = require ('express')
const router = Router()

router.get('/whome', function(req, res){
	logger.info('whome', req.user)
	return res.json(req.user)
})


router.get ('/hello', auth.isAuthenticated, async (req, res) => {
	res.json ({text:'hello'})
})

module.exports = router




我可以使用http://localhost/api/hello标题从邮递员那里拨打accept:application/javascript来获取:

{
    "text": "hello"
}

正如所料。但是,如果我从浏览器调用相同的URL(并且它没有发送该标头),我将获得创建的包index.html。如何从浏览器访问这些路线?

1 个答案:

答案 0 :(得分:1)

您有两种选择。

首先,尝试在服务器中添加:

app.options('*', cors())

之前:app.set("view engine", "pug")

如果不起作用,请尝试在addon中安装此Google Chrome browser进行测试。

Allow-Control-Allow-Origin: *

启用它。 (图标应为绿色而不是红色。)

为什么会这样? 正在进行的请求称为预检请求。 预检请求由浏览器提出,因为CORS仅是浏览器安全限制 - 这就是它在Postman中工作的原因,当然,它不是浏览器。

参考:Preflight request