![](/img/trans.png)
[英]NodeJS CORS error when calling api from localhost Vue project
[英]production calling api from localhost
我已經將我的應用程序(使用npm run build
)部署到了heroku。 但是,在heroku生產上完成的api調用來自我的本地主機。 我該如何改變? 有人可以請教嗎?
api_axios.js
const axios = require('axios')
export default () => {
return axios.create({
baseURL: 'https://myapp.herokuapp.com/api/' || 'http://localhost:1991/api/'
})
}
server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 1991
// express app
const app = express()
// middleware
app.use(cors())
// routes
const metrics = require('./routes/api/metrics')
app.use('/api/metrics', metrics)
// handle production
if(process.env.NODE_ENV === 'production'){
// static folder
app.use(express.static(__dirname + '/public/'))
// handle spa
app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'))
}
// run server
const server = app.listen(port, ()=>{
console.log(`server running on port ${port}`)
})
就像檢查服務器中的process.env.NODE_ENV
一樣,在編譯JavaScript時也應檢查環境。
您可以使用環境變量(通過如上所述的process.env
),配置文件(例如require('./config.json')
或您喜歡的任何其他方法。但是,到了一天結束時,您不應該硬編碼您的API URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.