前端使用vue2,如何使用axios向后端发送token,后端使用spirnboot框架,如何接收前端传过来的token,请用代码展示
时间: 2024-03-13 16:43:56 浏览: 44
前端代码示例:
```javascript
import axios from 'axios';
const token = 'your_token_here';
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axios.post('/api/your_endpoint', { data: 'your_data_here' })
.then(response => console.log(response))
.catch(error => console.error(error));
```
后端代码示例:
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@PostMapping("/api/your_endpoint")
public String yourEndpoint(@RequestBody YourRequestDto request) {
String token = request.getAuthorizationHeader();
// do something with the token
return "Success";
}
public static class YourRequestDto {
private String data;
private String authorizationHeader;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAuthorizationHeader() {
return authorizationHeader;
}
public void setAuthorizationHeader(String authorizationHeader) {
this.authorizationHeader = authorizationHeader;
}
}
}
```
在前端中,我们使用axios的`defaults.headers.common`属性来设置请求头部,即发送token,具体来说,我们设置了Authorization头部,值为Bearer加上token字符串。在后端中,我们使用`@RequestBody`注解来获取前端发送的数据,然后通过`YourRequestDto`类的`getAuthorizationHeader()`方法获取Authorization头部的值,即获取到了前端发送的token。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)