2

Access to XMLHttpRequest at 'https://api.hubapi.com/crm/v3/objects/contacts' from origin 'http://localhost:3001' 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.

I am trying to fetch data from hubspot by using API key. So I am getting errors like cors policies issues. To overcome that issue I have created node proxy server to get data from hubspot. By using below codes, I am getting data in different localhost like after calling get requests from reactjs, getting data from hotspot in localhost:3000/api but its supposed to come in the localhost3000 within the table format.

App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Container, Row, Col, Card } from 'react-bootstrap';

function ContactComponent() {
  const [contacts, setContacts] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);

  const pageSize = 10; // Number of contacts per page
  const apiKey = 'I have used my api key';

  useEffect(() => {
    async function fetchContacts() {
      try {
        const response = await axios.get(
          `https://api.hubapi.com/crm/v3/objects/contacts`
          , {
            headers: {
              Authorization: `Bearer ${apiKey}`
            }
          }
          //`https://api.hubapi.com/contacts/v1/lists/all/contacts/all?hapikey=${apiKey}&count=${pageSize}&vidOffset=${(currentPage - 1) * pageSize}`
        );

        const newContacts = response.data.contacts;
        setContacts(newContacts);
      } catch (error) {
        console.error('Error fetching contacts:', error);
      }
    }

    fetchContacts();
  }, [currentPage]);

  return (
    <Container>
      <h1>HubSpot Contacts</h1>
      <Row>
        {contacts.map(contact => (
          <Col key={contact.vid} xs={12} md={6} lg={4}>
            <Card className="mb-3">
              <Card.Body>
                <Card.Title>{contact.properties.firstname.value} {contact.properties.lastname.value}</Card.Title>
                <Card.Text>Email: {contact.properties.email.value}</Card.Text>
              </Card.Body>
            </Card>
          </Col>
        ))}
      </Row>
      <div className="text-center">
        <button
          className="btn btn-primary"
          onClick={() => setCurrentPage(prevPage => prevPage - 1)}
          disabled={currentPage === 1}
        >
          Previous Page
        </button>
        <button
          className="btn btn-primary ml-2"
          onClick={() => setCurrentPage(prevPage => prevPage + 1)}
        >
          Next Page
        </button>
      </div>
    </Container>
  );
}

export default ContactComponent;

Proxy server
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000; // Choose a port for the proxy server

const hubspotApiKey = ''; // Replace with your HubSpot API key

app.use(express.json());

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  next();
})
app.get('/hubspot-contacts', async (req, res) => {
  try {
    const hubspotResponse = await axios.get('https://api.hubapi.com/crm/v3/objects/contacts', {
      headers: {
        Authorization: `Bearer ${hubspotApiKey}`
      },
      params: {
        count: 10,
        vidOffset: req.query.vidOffset || 0
      }
    });

    res.json(hubspotResponse.data);
  } catch (error) {
    console.error('Error fetching HubSpot contacts:', error);
    res.status(500).json({ error: 'An error occurred' });
  }
});

app.listen(port, () => {
  console.log(`Proxy server is running on port ${port}`);
});


1 Answer 1

0

First API keys were deprecated back in November - HubSpot did make some exceptions (to my knowledge), but in general, API keys should no longer work for most accounts. You should use private apps instead.

Not sure if I understood your question correctly - but HubSpot, for security issues, doesn't support Ajax API requests (this will make the API key/public app token available to the public, which is a big security hole). What you're doing is correct - you are using server side scripting (Server A) for API requests, and then getting the data from your server (Server A) using Ajax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.