我在 Cakephp 3 中将 Angular 2 用于前端和后端。我在尝试登录时收到 401 Unauthorized 状态。我已经在 cakephp 3 中配置了 JWT,它在 POSTMAN 中运行良好。但不适用于 Angular。
这是我的 TypeScript 代码
loginToken(uname: string, pwd: string): Observable<boolean>{
let json = JSON.stringify({ username: uname , password: pwd});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost/crm/crm/api/users/token', json, options)
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser', JSON.stringify({ username: uname, token: token }));
return true; …Run Code Online (Sandbox Code Playgroud) 我正在使用 Angular 5 制作网络,每次尝试发出请求时都会收到此错误GET。我在这里阅读了大量的答案,但没有一个对我有用。
正如我所读到的,这是因为我正在向此请求添加自定义标头,这是需要完成的,因为我正在使用 Spring Security,我认为这是导致问题的原因。这是我当前的 Spring Security 配置,我通过阅读问题进行了配置,但仍然无法正常工作,我不知道我是否做错了什么:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests().anyRequest().permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable();
}
@Override
public void configure(WebSecurity web ) throws Exception
{
web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration …Run Code Online (Sandbox Code Playgroud) 我有一个在4200上本地运行的简单Angular App,我正在测试使用.net core在5000上本地运行的Web API。我的startup.cs具有正确配置的CORS以允许我相信的所有内容。
在ConfigureServices部分中,我有:
services.AddCors();
在配置部分中,我有:
app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
但是,当我尝试打我的webapi时,我仍然在浏览器中得到它。
来自源' http:// localhost:4200 '的信息已被CORS策略阻止:对预检请求的响应未通过访问控制检查:不允许对预检请求进行重定向。
我查看了其他答案,它们似乎都具有我尝试没有改变的这种或类似的变化。不知道我还需要做什么?
这是在后端和前端运行良好的 Express Route 代码。
// 按 Vessel_type by_id 编辑/更新 - 工作
router.put("/:id", (req, res, next) => {
Vessel_Type.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true },
(err, updatedRecord) => {
if (err) {
console.error(err);
return next(err);
} else {
res.status(200).send(updatedRecord);
}
}
);
});
Run Code Online (Sandbox Code Playgroud)
这是我在 React 前端使用nock进行 API 测试的代码
it("API test-3 - PUT (/api/vesseltype/id)", done => {
nock(host)
.defaultReplyHeaders({
"access-control-allow-origin": "*",
"Content-Type": "application/json"
})
.persist()
.log(console.log)
.put("/api/vesseltype/5c62cc8f1774b626cd7fdbe6", {
vesseltype: "Super Large Cargo Ship-45"
})
.delayBody(1000)
.reply(200, "PUT/EDIT data with reqheaders");
axios …Run Code Online (Sandbox Code Playgroud) 我正在尝试发出 PUT 请求,但出现以下错误:
Failed to load <localhost:8080/uaa/groups/dfsfaes8323df32>: Response for preflight does not have HTTP ok status.
Run Code Online (Sandbox Code Playgroud)
显然,当我发出 GET 和 POST 请求并在邮递员中工作时它有效,但它不适用于我的代码中的 PUT 请求。
这是我的要求:
let link = "https://ice.<mydomain>.com/uaadev/Groups/{groupId}";
link = link.replace("{groupId}", data);
const updLoad = {
displayName: this.groupInfoObjects.displayName,
description: this.groupInfoObjects.description,
zoneId : "uaa",
schemas: [
"urn:scim:schemas:core:1.0"
]
};
let Header = new Headers({
Authorization: `Bearer {token}`.replace("{token}", this.token),
"Content-Type": "application/json",
Accept: "application/json",
"if-Match":"*"
});
let Option = new RequestOptions({ headers: Header });
this.http.put(link, updLoad, Option).subscribe(
res => {
console.log(res);
console.log(res.status);
if …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过 AWS API Gateway 创建一个 API 测试函数,以及一个通过 Axios 的 Vue 应用程序调用的 Lambda 函数。它应该从输入元素发送姓名和电子邮件。每次我收到此错误时:
Access to XMLHttpRequest at '[API Gateway URL]' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Run Code Online (Sandbox Code Playgroud)
我已在 API 网关设置中的每个步骤/资源上启用了 CORS(根据本文)。下面是 Vue 组件的代码:
<template>
<div data-app>
<div class="cell" id="testForm">
{{responseMsg}}
<label>Name</label>
<input v-model="name" type="text" placeholder="Name">
<label>Email Address</label>
<input v-model="email" type="email" placeholder="Email Address">
<button v-on:click="formFunction">Submit</button>
</div>
</div>
</template>
<script>
import axios …Run Code Online (Sandbox Code Playgroud) ?你好,
我的HTTP请求有问题。是否可以帮助我了解发生了什么?
当我发送GET请求时,它作为OPTIONS发送:
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8')
?.set('Authorization','bearer ' + this.auth.getUserToken());
this.http.get(SERVER.URL_PROD + API.VERSION + API.GET_USERS, {headers: headers}).subscribe((res: any) => {
console.log(res);
});
Run Code Online (Sandbox Code Playgroud)
在我的chrome开发工具调试中,我看到以下内容:
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Run Code Online (Sandbox Code Playgroud) angular ×5
cors ×4
preflight ×2
angular6 ×1
asp.net-core ×1
aws-lambda ×1
axios ×1
cakephp-3.0 ×1
express ×1
get ×1
http ×1
http-headers ×1
jwt ×1
nock ×1
node.js ×1
reactjs ×1
rest ×1
spring-boot ×1
vue.js ×1