Javascript .env文件无法传递字符串值
我在一个react项目中工作,当直接输入字符串值时,API调用成功完成。使用.env文件时失败Javascript .env文件无法传递字符串值,javascript,node.js,Javascript,Node.js,我在一个react项目中工作,当直接输入字符串值时,API调用成功完成。使用.env文件时失败 require('dotenv').load(); export default () => { const postToApi = (event) => { event.preventDefault(); axios.post(process.env.API_POST_URL, {step : "3"}) .then(res => {
require('dotenv').load();
export default () => {
const postToApi = (event) => {
event.preventDefault();
axios.post(process.env.API_POST_URL, {step : "3"})
.then(res => {
console.log(res);
console.log(res.data);
})
};
下面是根项目文件夹中的.env文件:
NODE_PATH=./node_modules
API_POST_URL=http://localhost:4000/api/donate
执行上述功能时出现浏览器控制台错误:
isURLSameOrigin.js:51 Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
at isURLSameOrigin (isURLSameOrigin.js:51)
at dispatchXhrRequest (xhr.js:106)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js:18)
at dispatchRequest (dispatchRequest.js:49)
isURLSameOrigin.js:51未捕获(承诺中)类型错误:无法读取未定义的属性“协议”
在isURLSameOrigin(isURLSameOrigin.js:51)
在dispatchXhrRequest(xhr.js:106)
在新的承诺()
在xhrAdapter(xhr.js:18)
应dispatchRequest(dispatchRequest.js:49)
package.json依赖项对象列表:“dotenv”:“^6.1.0”
有人知道变量传递不正确的原因吗?您不需要在qoutes中的env文件中放入字符串,例如
NODE\u PATH=“./NODE\u modules”
如果console.log(process.env.API\u POST\u URL),您会得到什么代码>
刚刚检查了dotenv文档,它说使用'require('dotenv').config()'constpath=require('path')
require('dotenv').config({path:path.join(uu dirname,...env'))}) 出现这个问题仅仅是因为dotenv.config({path://.config/config.env})代码>
路径不正确,我应该使用dotenv.config({path:“./config/config.env”})代码>
仔细检查路径。好的,我刚刚尝试在.env文件中的字符串值周围添加双引号。它会导致同样的错误,不幸的是,这应该是一个注释而不是答案,并且您不需要在.env
文件中加引号,默认情况下,它会读为stringIt,直到50次重复才允许添加注释,奇怪的是,我可以对你的评论发表评论。你是否也使用NPM安装了dotenv?这个问题发生在不久前,但我相信修复方法是在env变量键中添加前缀REACT\u APP
。React在使用create React app时安装dotenv并自行加载。