美文网首页
React项目 fetch 本地json文件 404问题

React项目 fetch 本地json文件 404问题

作者: 永和包仔 | 来源:发表于2022-09-22 17:12 被阅读0次

今天在二开修改开源项目的时候,想要在React项目中,fetch远程json改为本地的json文件却一直报404
网上的解决方案,收集了几点:

  • 地址都是相对于首页index.html而言,将json数据放在相对index.html上就好了
  • 在'./Data/in_theaters.json'前面加上json! 'json!./Data/in_theaters.json',webpack在3之后就不需要json-loader了
  • 虚拟服务器 Webpack-DevServer 与contentBase 这个属性有关系,配置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? }

项目代码

项目结构如下:


image.png

调用的代码如下:

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)
  })
}

解决

根据找到的诸多解释,肯定还是落在路径问题,即webpack配置上。回看刚才配置了contextBase出错的提示信息,显示了server可以支持选项

image.png

根据官方的文档:


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
      }
    }
  },

相关文章

网友评论

      本文标题:React项目 fetch 本地json文件 404问题

      本文链接:https://www.haomeiwen.com/subject/mtpnortx.html