【发布时间】:2021-11-26 19:11:15
【问题描述】:
我正在尝试使用 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);
}
...
}
【问题讨论】: