![](/img/trans.png)
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource (Spring)
[英]Axios Post in react js is giving error No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在嘗試使用后端的Spring Boot在我的Web應用程序中使用react創建登錄頁面。 我正在使用Spring Security JDBC身份驗證進行登錄。 我正在嘗試將我的JSP頁面轉換為React。 使用JSP和spring boot,登錄正常。 現在,我試圖用react創建同一頁面。 但是當我使用axios發布時,我得到錯誤
從源' http:// localhost:3000 '到' http:// localhost:8080 / onlineshopping / login '處對XMLHttpRequest的訪問已被CORS策略阻止:在服務器上沒有'Access-Control-Allow-Origin'標頭要求的資源。
這是axios Post
export const Login = (username, password) => async dispatch => {
console.log(password)
let params = {
username: username,
password: password
}
const res = await axios.post("http://localhost:8080/onlineshopping/login", {params});
dispatch({
type: Login,
payload: res.data
});
};
SecurityConfig.java
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.usersByUsernameQuery("select email, password, enabled from user_detail where email = ?")
.authoritiesByUsernameQuery("select email, role from user_detail where email = ?")
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
}
Pagecontroller.java
@RestController
@CrossOrigin
public class PageController {
@RequestMapping("/login")
public Map<String, Object> login(
@RequestParam(name = "error", required = false) String error,
@RequestParam(name = "logout", required = false) String logout) {
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("Login");
map.put("title", "Login");
if (error != null) {
map.put("message", "Username and Password is invalid!");
}
if (logout != null) {
map.put("logout", "You have logged out successfully!");
}
return map;
}
}
請告訴我為什么我收到此錯誤以及如何解決。
您必須為API調用創建代理。
在這里,代理使用url模式來匹配api調用,並將它們重定向到相應的服務器。
請嘗試以下操作:
安裝http-proxy-middleware
npm install http-proxy-middleware --save
創建src / setupProxy.js
const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use(proxy('/api', { target: 'http://localhost:8080/' })); };
然后運行本地開發服務器
您必須將代理地址添加到package.json文件,例如:
},
"proxy": "http://localhost:8080",
"devDependencies": {
接下來,您只需添加所有在localhost之后的內容,即
axios.get("/onlineshopping/login")
在Spring Boot中將CORS過濾器配置和內容類型添加到axios中的application / x-www-form-urlencoded后,我的問題解決了。
export const addProjectTask = (username,password, history) => async dispatch => {
axios.post('http://localhost:8080/onlineshopping/login',
Qs.stringify({
username: username,
password: password
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}})
.then(function (response) {
console.log(response);
history.push("/");
})
.catch(function (error) {
console.log(error);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.