【发布时间】:2023-02-02 00:52:18
【问题描述】:
当站点以开发方式“npm start”运行时,使用的后端 url 来自 package.json 的代理。
当我选择生产方式“npm build”时,不使用 package.json 中的后端 url,因为该代理仅用于开发。
我需要一些帮助来了解如何配置后端 url,我在开发和生产中使用相同的 url。
在配置文件.package.json 中:
{
"name": "mysite_frontend_v1",
"version": "0.1.0",
"private": true,
"proxy": "https://api.mysite.com",
...
}
然后创建了一个文件 .env :
REACT_APP_API_URI = 'https://api.mysite.com'
api.js 文件:
function request(path, { data = null, token = null, method = 'GET' }) {
return fetch(path, {
method,
headers: {
Authorization: token ? `Token ${token}` : '',
'Content-Type': 'application/json',
},
body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(data) : null,
})
.then((response) => {
// If it is success
if (response.ok) {
if (method === 'DELETE') {
// If delete, nothing return
return true;
}
return response.json();
}
// Otherwise, if there are errors
return response
.json()
.then((json) => {
// Handle JSON error, response by the server
if (response.status === 400) {
const errors = Object.keys(json).map((k) => `${json[k].join(' ')}`);
throw new Error(errors.join(' '));
}
throw new Error(JSON.stringify(json));
})
.catch((e) => {
throw new Error(e);
});
})
.catch((e) => {
// Handle all errors
toast(e.message, { type: 'error' });
});
}
export function signIn(username, password) {
return request('/auth/token/login/', {
data: { username, password },
method: 'POST',
});
}
export function register(username, password) {
return request('/auth/users/', {
data: { username, password },
method: 'POST',
});
}
【问题讨论】:
标签: reactjs