我正在尝试从 React JS Web 应用程序登录鳄梨酱。 我的鳄梨酱服务器在tomcat服务器上,我的react应用程序在node js上;两者都在不同的域上。我在服务器上使用了 nagix 代理,但仍然收到 cors 错误。
const baseURL = 'http://myurl/api'; // Replace with your Guacamole server URL
const username1 = username; // Replace with your Guacamole username
const password1 = password; // Replace with your Guacamole password
// Define the API endpoint for authentication
const authEndpoint = '/tokens';
// Create a basic authentication header with your username and password
const authHeader = {
'Authorization': 'Basic ' + Buffer.from(`${username1}:${password1}`).toString('base64'),
};
// Step 1: Authenticate and obtain a token
axios.post(baseURL + authEndpoint, { headers: authHeader })
.then(response => {
const authToken = response.data.authToken;
console.log('Authentication Token:', authToken);
// Step 2: Use the authentication token for subsequent requests
const headers = {
'Authorization': `Bearer ${authToken}`,
};
// Define the API endpoint for the subsequent request
const apiEndpoint = '/session/data'; // Modify this as needed for other API endpoints
console.log(apiEndpoint)
axios.get(baseURL + apiEndpoint, { headers })
.then(response => {
console.log('Active Sessions:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
})
.catch(error => {
console.error('Authentication Error:', error.message);
});
}
首先需要在 web.xml 文件中进行 cors 配置,该文件位于 ubuntu 中的 ar\lib omcat9\webapps\guacamole\WEB-INF/web.xml 中。我在 localhost:3000 中运行 React 示例应用程序。现在在 web.xml 中添加您的 cors 来源。这是示例配置。之后重新启动 guacd 服务。
<filter>
<filter-name>cacheRevalidationFilter</filter-name>
<filter-class>org.apache.guacamole.CacheRevalidationFilter</filter-class>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cacheRevalidationFilter</filter-name>
<url-pattern>/index.html</url-pattern>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>