今天在二開修改開源項目的時候,想要在React項目中,fetch遠程json改為本地的json文件卻一直報404
網(wǎng)上的解決方案,收集了幾點:
- 地址都是相對于首頁index.html而言,將json數(shù)據(jù)放在相對index.html上就好了
- 在'./Data/in_theaters.json'前面加上json! 'json!./Data/in_theaters.json',webpack在3之后就不需要json-loader了
- 虛擬服務(wù)器 Webpack-DevServer 與contentBase 這個屬性有關(guān)系,配置
contentBase: path.join(__dirname, 'src'), 添加后報錯
options has an unknown property 'contentBase'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?
, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, o
pen?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
項目代碼
項目結(jié)構(gòu)如下:

image.png
調(diào)用的代碼如下:
import url from 'url'
import querystring from 'querystring'
import style from './style.js'
export function initialStyleUrl() {
const initialUrl = url.parse(window.location.href, true)
return (initialUrl.query || {}).style
}
export function loadStyleUrl(styleUrl, cb) {
console.log('Loading style', styleUrl)
fetch(styleUrl, {
mode: 'cors',
credentials: "same-origin"
})
.then(function(response) {
return response.json();
})
.then(function(body) {
cb(style.ensureStyleValidity(body))
})
.catch(function() {
console.warn('Could not fetch default style', styleUrl)
cb(style.emptyStyle)
})
}
解決
根據(jù)找到的諸多解釋,肯定還是落在路徑問題,即webpack配置上。回看剛才配置了contextBase出錯的提示信息,顯示了server可以支持選項

image.png
根據(jù)官方的文檔:

image.png

image.png
綜上,配置上static選項,問題解決
devServer: {
// enable HMR
hot: true,
// serve index.html in place of 404 responses to allow HTML5 history
historyApiFallback: true,
port: PORT,
host: HOST,
static: path.join(__dirname, '../src'),//add static style.json can used http in localhost
watchFiles: {
options: {
// Disabled polling by default as it causes lots of CPU usage and hence drains laptop batteries. To enable polling add WEBPACK_DEV_SERVER_POLLING to your environment
// See <https://webpack.js.org/configuration/watch/#watchoptions-poll> for details
usePolling: (!!process.env.WEBPACK_DEV_SERVER_POLLING ? true : false),
watch: false
}
}
},