arv*_*ind 6 javascript express graphql react-apollo prisma-graphql
我在这里使用了一个 graphql 棱镜后端和一个 graphql 瑜伽快递服务器。在前端,我试图调用注销突变,但它被 CORS 策略阻止。尽管我在我的 graphql 瑜伽服务器中添加了 cors 设置,但我不断收到此错误。GraphQL 查询工作正常,但突变被阻止。我的前端 URL 是“ http://localhost:7777 ”,而yoga服务器运行在“ http://localhost:4444/ ”。错误是:
Access to fetch at 'http://localhost:4444/' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
[Network error]: TypeError: Failed to fetch
Run Code Online (Sandbox Code Playgroud)
GraphQL Yoga 服务器 Cors 配置:
server.start(
{
cors: {
credentials: true,
origin: [process.env.FRONTEND_URL],
},
},
deets => {
console.log(
`Server is now running on port http://localhost:${deets.port}`
);
}
);
Run Code Online (Sandbox Code Playgroud)
突变:
// import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import styled from 'styled-components';
import gql from 'graphql-tag';
import { CURRENT_USER_QUERY } from './User';
import { log } from 'util';
const SIGN_OUT_MUTATION = gql`
mutation SIGN_OUT_MUTATION {
signout {
message
}
}
`;
const SignOutBtn = styled.button`
color: ${props => props.theme.textMedium};
padding: 10px;
margin-right: 20px;
text-align: center;
font-family: garamond-light;
border: 1px solid ${props => props.theme.textMedium};
border-radius: 5px;
transition: background-color 0.5s ease;
transition: color 0.5s ease;
:hover {
background: ${props => props.theme.textMedium};
color: ${props => props.theme.white};
}
`;
const Signout = props => (
<Mutation
mutation={SIGN_OUT_MUTATION}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{signout => (
<SignOutBtn
onClick={() => {
console.log("comes here")
signout();
}}
>
Sign Out
</SignOutBtn>
)}
</Mutation>
);
export default Signout;
Run Code Online (Sandbox Code Playgroud)
请告诉我我在这里做错了什么。提前致谢。
该问题的解决方案是编写一个中间件来设置适当的响应标头,以便获取不会失败。
server.express.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:7777');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
Run Code Online (Sandbox Code Playgroud)
以上就是用于解决该问题的yogaexpress服务器中间件。
| 归档时间: |
|
| 查看次数: |
2396 次 |
| 最近记录: |