next.js icon indicating copy to clipboard operation
next.js copied to clipboard

localhost:3000 has been blocked by CORS policy

Open aesthytik opened this issue 7 years ago • 9 comments

Bug report

Describe the bug

I added google autosuggestions API in my nextjs app and it gave me following error

'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=jalandhar&key=API KEY' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please help or provide some other solution. i want to add google search in my web app.

System information

  • OS: macOS
  • Browser:Chrome
  • Version of Next.js: latest

aesthytik avatar Aug 28 '19 13:08 aesthytik

Hi, this is a general web development question that is unrelated to Next.js.

You may find help or a solution on Stack Overflow or by asking in our community Spectrum.

That said, you probably need to create an API route that proxies this google API.

Timer avatar Aug 28 '19 13:08 Timer

You should update the next.js tutorial with a recommended fix to continue to lesson:

https://nextjs.org/learn/basics/fetching-data-for-pages/fetching-data-for-pages

alanlupsha avatar Oct 01 '19 16:10 alanlupsha

For anyone who is facing this, always check the Next.js examples folder, since there is a lot of things solved like this one

@alanlupsha

https://github.com/zeit/next.js/tree/canary/examples/with-custom-reverse-proxy

carloscuesta avatar Oct 09 '19 06:10 carloscuesta

@aesthytik,

I solved by doing the following steps:

  1. $ npm install --save-dev http-proxy-middleware https://www.npmjs.com/package/http-proxy-middleware

  2. Create setUpProxy.js in your react src folder.

  3. Add this content in setUpProxy.js that you just created.

const { createProxyMiddleware } = require('http-proxy-middleware');

// restream parsed body before proxying var restream = function(proxyReq, req, res, options) { if (req.body) { let bodyData = JSON.stringify(req.body); // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json proxyReq.setHeader('Content-Type','application/json'); proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); // stream the content proxyReq.write(bodyData); } }; module.exports = function(app) { app.use( createProxyMiddleware("/(your targetted path)",{ target:"(your targetted domain name)", secure:false, changeOrigin:true, onProxyReq:restream }) );

//if you have more than one url, add app.use as much as you want as shown below app.use( createProxyMiddleware("/(your targetted path)",{ target:" (your targetted domain name)", secure:false, changeOrigin:true, onProxyReq:restream }) ); };

  1. Restart your app with "npm start".

Hope you find this helpful!

sapphireJena avatar Jun 27 '20 13:06 sapphireJena

Hey @aesthytik

You were using next js for your app. How did you solve it with next js? I'm getting the following error: Access to XMLHttpRequest at 'https://api.twitter.com/1.1/trends/place.json?id=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Thanks!

anujparekh18 avatar Dec 17 '20 06:12 anujparekh18

@anujparekh18

First - You should not request network from non-secure url, even from development environment. Please use https for development. Second - CORS is security feature on the backend, which restricts access to the list of allowed domain names. You have to add your https://localhost:3000 to your api key access settings in twitter.

JustFly1984 avatar Dec 23 '20 02:12 JustFly1984

@anujparekh18 @aesthytik I was also getting a similar error while calling the remote APIs from the client side in next.js.

How I solved it?

  1. Instead of calling remote APIs from the client side, create a new API under pages/api/ folder.
  2. Call the remote API from the API you created in pages/api/ by using next-connect middleware and cors.

For example:

Create a new API

// pages/api/example.js

import nc from "next-connect";
import cors from "cors";

const handler = nc()
  // use connect based middleware
  .use(cors())
  .post(async (req, res) => {
    const response = await fetch(remoteServerUrl, config);
    res.json(response);
  });

export default handler;

Call that API from client side

// pages/index.js

// wrong way
const fetchData = async () => {
     const response = await fetch(remoteServerUrl, config);
     const data = response.json();
}

// correct way
const fetchData = async () => {
     const response = await fetch("/api/example", config);
     const data = response.json();
}

I hope it helps.

rahuldkjain avatar Jan 31 '21 08:01 rahuldkjain

@anujparekh18 @aesthytik I was also getting a similar error while calling the remote APIs from the client side in next.js.

How I solved it?

  1. Instead of calling remote APIs from the client side, create a new API under pages/api/ folder.
  2. Call the remote API from the API you created in pages/api/ by using next-connect middleware and cors.

For example:

Create a new API

// pages/api/example.js

import nc from "next-connect";
import cors from "cors";

const handler = nc()
  // use connect based middleware
  .use(cors())
  .post(async (req, res) => {
    const response = await fetch(remoteServerUrl, config);
    res.json(response);
  });

export default handler;

Call that API from client side

// pages/index.js

// wrong way
const fetchData = async () => {
     const response = await fetch(remoteServerUrl, config);
     const data = response.json();
}

// correct way
const fetchData = async () => {
     const response = await fetch("/api/example", config);
     const data = response.json();
}

I hope it helps.

 const data = response.json();

this line needs await -> const data = await response.json();

but thanks for your help <3

brothanek avatar Oct 29 '21 18:10 brothanek

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

balazsorban44 avatar Jan 27 '22 13:01 balazsorban44