我正在嘗試使用 axios.post(在 TS 中)從服務器獲取回應(使用 POST 作為 GET)而不發送任何資料。服務器發回資料,但 REACT 無法處理回應。
這是反應組件:
interface allComapnies {
comapniesData:CompanyData[];
}
function GetAllCompanies(props:allComapnies): JSX.Element {
const myURL = globals.urls.admin "get_company/all";
const [comapniesData,setData] = useState([new CompanyData()]);
useEffect(()=>{axios.post(myURL).then((response)=>{
console.log(response.data);
setData(response.data);
}).catch(error=>{console.log(error)});
},[]);
return (
<div className="getAllCompanies">
{comapniesData.map(item=><OneCompany
key ={item.id}
id={item.id}
name={item.name}
email={item.email}
/>)}
</div>
);
}
export default GetAllCompanies;
控制臺訊息顯示:
錯誤:請求失敗,狀態碼為 302
- 在 createError (createError.js:16)
- 在解決 (settle.js:17)
- 在 XMLHttpRequest.onloadend (xhr.js:54)
瀏覽器從服務器獲取回應:
[{id: 2, name: "company2", email: "hgfytj@fdgreg", password: "trjyjytk",...},...]
Server(SPRING)中Controller內部REST Post的作用:
@RestController
@RequestMapping("admin")
@CrossOrigin(origins = "localhost:3000", allowedHeaders = "*")
@RequiredArgsConstructor
public class AdminController extends ClientController {
private final AdminService adminService;
...
@PostMapping("get_company/all")
public ResponseEntity<?> getAllCompanies() {
return new ResponseEntity<>(adminService.getAllCompanies(), HttpStatus.FOUND);
}
...
}
uj5u.com熱心網友回復:
嘗試 GET 方法而不是 POST 因為您從資料庫獲取資料而不是將其發送到。
uj5u.com熱心網友回復:
您正在嘗試getAllCompanies從后端服務獲取 ,因此您必須使用標準GET方法而不是POST方法。
獲取getAllCompanies不需要發送額外的資料。在這種情況下,通常需要通過標頭發送令牌。
此外,嘗試使用以下最佳實踐呼叫異步 Axios 函式useEffect:
useEffect(() => {
// first define the asyn function
async function getAllCompanies() {
try {
const response = await axios.get(baseUrl "get_company/all")
setData(response.data);
} catch(error) {
// console.log(error)
}
}
// now, call it
getAllCompanies();
},[]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312528.html
