Home > Web Front-end > Front-end Q&A > Where to configure nodejs cross domain

Where to configure nodejs cross domain

PHPz
Release: 2023-04-17 17:09:46
Original
751 people have browsed it

When making cross-domain requests in the Node.js environment, specific configuration is required to make the request proceed normally. So, where exactly is cross-domain configuration done?

First of all, we need to understand what a cross-domain request is. Cross-origin requests refer to requests initiated by the client when accessing a URL different from the source of the current page. Due to the browser's same-origin policy restrictions, such requests are prohibited from being sent. Because Node.js can run as a web server, it also requires cross-domain configuration to meet special needs.

There are usually two ways to perform cross-domain configuration in Node.js, namely configuration on the server side and configuration on the client side.

  1. Configuration on the server side

In Node.js, you can use the cors module to configure cross-domain requests. Before using the cors module, you need to install it first:

npm install cors
Copy after login
Copy after login

After the installation is completed, when using it, you only need to introduce the module:

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

// ...
Copy after login

Among them, app.use(cors()) means allowing all domains to access. If you need to authorize access to a specific domain, you can use the following method:

const express = require('express');
const cors = require('cors');

const app = express();

const corsOptions = {
  origin: 'http://example.com'
}

app.use(cors(corsOptions));

// ...
Copy after login

In the example, corsOptions specifies that the http://example.com address is allowed. Cross-origin requests.

  1. Configure on the client

If you need to initiate a cross-domain request in the client page, you can also use the cors module for configuration. When using the cors module on the client, you need to install it first:

npm install cors
Copy after login
Copy after login

After the installation is completed, you can configure the following in the client code when using it:

const axios = require('axios');
const cors = require('cors');

const corsOptions = {
  origin: 'http://example.com'
};

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.post['Access-Control-Allow-Headers'] = 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With';
axios.defaults.headers.post['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS';

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 1000,
});

instance.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

instance.defaults.withCredentials = true;

instance.defaults.transformRequest = [function(data) {
  data = JSON.stringify(data);
  return data;
}];

instance.defaults.transformResponse = [function(data) {
  if (typeof data === 'string' && data.includes('{') && data.includes('}')) {
    data = JSON.parse(data);
  }
  return data;
}];

instance.interceptors.request.use(function(config) {
  config.withCredentials = true;
  return config;
}, function(error) {
  return Promise.reject(error);
});

instance.interceptors.response.use(function(response) {
  return response;
}, function(error) {
  return Promise.reject(error);
});

instance.use(cors(corsOptions)); 

// ...
Copy after login

Among them, instance.use(cors(corsOptions)) indicates that the http://example.com address is allowed to make cross-domain requests.

In summary, cross-domain requests in the Node.js environment can be configured on the server side or on the client side. It is necessary to choose the appropriate method for cross-domain configuration according to the actual scenario.

The above is the detailed content of Where to configure nodejs cross domain. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template