오리진 'http://localhost:3000'에서 가져올 액세스가 CORS 정책에 의해 차단되었습니다.
데이터베이스에 추가하면 오류가 표시됩니다.어떻게 해야 하나?
오리진 'http://localhost:3000'에서 'http:xx'로 가져오기 위한 액세스가 CORS 정책에 의해 차단되었습니다.비행 전 요청에 대한 응답이 액세스 제어 검사를 통과하지 못했습니다.요청된 리소스에 'Access-Control-Allow-Origin' 헤더가 없습니다.불투명한 응답이 요구에 적합한 경우 요청 모드를 'no-cors'로 설정하여 CORS가 비활성화된 상태로 리소스를 가져옵니다.
기능:
addItem = (e) => {
e.preventDefault();
const ob = {
X: 53.0331258,
Y: 18.7155611,
}
fetch("http://xxx", {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(ob)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
}
"no-time" 모드를 사용해 보십시오.
fetch('http://localhost:8080/example', {
mode: 'no-cors',
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(ob)
})
서버는 다음과 같은 응답으로 응답해야 합니다.
Access-Control-Allow-Origin: https://localhost:3000
회피책으로 설정할 수 있을 때까지 아래의 크롬 확장을 설치하여 테스트를 재개할 수 있습니다.
https://chrome.google.com/webstore/detail/who-cors/hnlimanpjeeomjnpdglldcnpkppmndbp?hl=en-GB
그러나 위의 내용은 개발을 계속하기 위한 회피책일 뿐입니다.
이 기사를 읽고 CORS를 이해하시길 권합니다.https://javascript.info/fetch-crossorigin
코르스를 설치해야 합니다.
npm install cors
메인 스크립트 index.displaces 또는 app.displaces 내부
const cors = require("cors");
app.use(cors());
이 문제를 해결하려면cors노드 모듈 및 이를 요청된 서버에 추가
const cors = require("cors");
app.use(cors());
브라우저의 경우 CORS는 기본적으로 활성화되어 있으며 클라이언트 측 앱(스태틱 파일)을 제공하지 않은 서버에 요청을 전송해도 좋다는 것을 브라우저에 알려야 합니다.
노드 및 express와 함께 RestFul API를 사용하는 경우 이 미들웨어를 파일에 추가합니다.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
})
다음 코드를 사용해 보십시오.
var corsOptions = {
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
server.js(또는 app.js)로 복사해야 합니다.
(I've experienced the exact same problem as this one. I was able to solve the problem by adding the following code to server.js.)
미들웨어는 이렇게 되어 있어야 합니다.
app.use((req, res, next) => {
res.header({"Access-Control-Allow-Origin": "*"});
next();
})
const cors = required parames"; app.use(faram();
나는 이것을 사용하지만 이 문제를 해결할 수 없다.
app.use((req, res, next) => {res.header({"Access-Control-Allow-Origin"): "*"}; next(); })
주석을 달려고 하다@CrossOrigin, 그것은 나에게 효과가 있었다.
@RestController @RequestMapping(value="") @CrossOrigin
WordPress 버전 6에서는 fetch api에서 사용할 수 있는 모드 옵션을 사용하여 문제를 해결했습니다.
apiFetch( { mode: 'no-cors', url: 'https://api.example.com/?q=' + attributes.search_string } ).then( ( posts ) => {
console.log( posts );
} );
실제로 서버 측에서 다음과 같이 이 오류를 수정하는 것이 더 효율적입니다.
npm install cors
포스트 조작 내부:
app.post("/...", (req, res) =>{
res.set('Access-Control-Allow-Origin', '*');
//whatever you want here
}
다음 기사 https://www.stackhawk.com/blog/react-cors-guide-what-it-is-and-how-to-enable-it/ #enable-display-on-server-side 를 참조해 주세요.
또는 패키지를 추가하는 것으로, 클라이언트측을 서버측과 같은 도메인상에서 동작하도록 간단하게 변환할 수 있습니다.다음과 같이 서버 도메인의 json(클라이언트 측) "syslog"를 지정합니다.
"proxy": "http://xxxx/"
이 경우 각 요청에 도메인 이름을 추가할 필요가 없습니다.
마지막 솔루션은 {"mode": "no-display"}을(를) 요청에 추가하여 "권장되지 않음"으로 설정합니다.
헤더라는 새로운 변수를 만듭니다.
const header = new Headers({ "Access-Control-Allow-Origin": "*" });
이 변수를 가져오기 개체로 전달합니다.
fetch(url, { header: header })
.then((res) => res.json())
.then((data) => console.log(data));
이것으로 문제가 해결됩니다.
언급URL : https://stackoverflow.com/questions/61238680/access-to-fetch-at-from-origin-http-localhost3000-has-been-blocked-by-cors
'source' 카테고리의 다른 글
| mat-form-field에는 MatFormFieldControl이 포함되어야 합니다. (0) | 2023.03.04 |
|---|---|
| 각도 JS: 제출하기 전에 양식 필드 유효성 확인 (0) | 2023.03.04 |
| Wordpress - 게시 화면에 사용자 지정 필드 추가 (0) | 2023.03.04 |
| 반응 테이블의 CSV로 내보내기 버튼 (0) | 2023.03.04 |
| How can I get all a form's values that would be submitted without submitting (0) | 2023.03.04 |