Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js axios无法随请求发送cookie,即使withCredential:true_Node.js_Reactjs_Cookies_Cors_Axios - Fatal编程技术网

Node.js axios无法随请求发送cookie,即使withCredential:true

Node.js axios无法随请求发送cookie,即使withCredential:true,node.js,reactjs,cookies,cors,axios,Node.js,Reactjs,Cookies,Cors,Axios,我已经在这样的服务器上安装了 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-PINGOTHER'

我已经在这样的服务器上安装了

    app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,  X-PINGOTHER'
  );
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
  next();
});
axios.defaults.withCredentials = true;
axios('http://127.0.0.1:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })
客户端的axios(反应)如下

    app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,  X-PINGOTHER'
  );
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
  next();
});
axios.defaults.withCredentials = true;
axios('http://127.0.0.1:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })

当我用Postman测试并直接在chrome上打字时,一切都很好。知道我的代码出了什么问题吗?

我找出了我的错误。将axios代码更改为

axios.defaults.withCredentials = true;
axios('http://localhost:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })

我仍然想问,为什么这一更改会有帮助,所以如果您计划多次使用此选项,请提供任何答案,然后创建一个axios配置:

client/src/utils/axioconfig.js

import axios from 'axios';

const baseURL = process.env.NODE_ENV === "development"
  ? "http://localhost:3001/"
  : "http://example.com"

const app = axios.create({
    baseURL,
    withCredentials: true
})

/* 
  The below is required if you want your API to return 
  server message errors. Otherwise, you'll just get 
  generic status errors.

  If you use the interceptor below, then make sure you 
  return an err message from your express route: 

  res.status(404).json({ err: "You are not authorized to do that." })

*/
app.interceptors.response.use(
  response => (response), 
  error => (Promise.reject(error.response.data.err))
)

export default app;
import app from '../utils/axiosConfig';

export const exampleAction = () => (
  app.get('orders') // this will be defined as baseURL + "orders" (http://localhost:3001/orders)
    .then(res => console.log(res))
    .catch(err => console.log(err))
)
client/src/actions/exampleAction.js

import axios from 'axios';

const baseURL = process.env.NODE_ENV === "development"
  ? "http://localhost:3001/"
  : "http://example.com"

const app = axios.create({
    baseURL,
    withCredentials: true
})

/* 
  The below is required if you want your API to return 
  server message errors. Otherwise, you'll just get 
  generic status errors.

  If you use the interceptor below, then make sure you 
  return an err message from your express route: 

  res.status(404).json({ err: "You are not authorized to do that." })

*/
app.interceptors.response.use(
  response => (response), 
  error => (Promise.reject(error.response.data.err))
)

export default app;
import app from '../utils/axiosConfig';

export const exampleAction = () => (
  app.get('orders') // this will be defined as baseURL + "orders" (http://localhost:3001/orders)
    .then(res => console.log(res))
    .catch(err => console.log(err))
)
然后,对于您的API,您可以在定义
express
中间件的任何地方使用,而不是指定CORS头:

const cors = require('cors');
const origin = process.env.NODE_ENV === "development" 
  ? "http://localhost:3000" 
  : "http://example.com"

app.use(
  cors({
    credentials: true,
    origin
  }),
);

我发现这篇文章很有帮助:

但可能取决于服务器设置

在客户端集Axios标头中:

headers: {Authorization: `Bearer ${cookie_value}`},
withCredentials: true,
crossDomain: true

现在,Chrome在跨域cookie设置中添加了更多恼人的限制,您必须将带有
SameSite
的cookie设置为
none
,否则Chrome将拒绝发送cookie。此外,如果设置了SameSite,则必须设置
安全

下面是如何在nginx中设置此更改的示例,它可能不适用于您的情况,但仅供参考

proxy_cookie_path / "/; secure; SameSite=none";

您是将cookies设置为服务器端还是客户端?您需要确保cookie没有设置为仅http标志。如果你打开chrome开发者工具,进入“应用程序”,然后进入“Cookies”,并检查是否有检查,你可以检查他们是否有此标志(✓) HTTP列中的图标。@RalphNajm哦,这实际上是我的错误,我没有将其设置为仅HTTP。谢谢,它现在可以工作。欢迎:)救生圈!!!!!