Rafael Souza
Rafael Souza

Reputation: 1351

send nextjs post to nodejs api

how to send post to api nodejs with nextjs my error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http: // localhost: 4000 / contact / cadastre. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) but no node has no limitation for cors. when I put he registers

import Layout from "../components/Layout";
import { NextPage } from 'next';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Alert from '@material-ui/lab/Alert';

const Contato: NextPage = () => (  
   
    <Layout title="Página - Contato" description="desenvolvimento web, web development, construção de sites" 
    title_meta="desenvolvimento web, web development, construção de sites"
    description_meta="desenvolvimento web, web development, construção de sites" site_name="Rafael Web development"
    url="http://localhost:3000/">
        <div>
        <h1>Contato</h1>
        <form>
          <Alert severity="error" id="error_contact" style={{display:"none",marginBottom:20}}>Erros:<br /></Alert>
          <TextField id="outlined-nome" label="Nome" name="nome" type="text" variant="outlined"  
          style={{width:"100%",paddingBottom:20}} />
          <TextField id="outlined-email" label="E-mail" name="email" type="text" variant="outlined" 
          style={{width:"100%",paddingBottom:20}}  />
          <TextField id="outlined-assunto" label="Assunto" name="assunto" type="text" variant="outlined" 
          style={{width:"100%",paddingBottom:20}}  />
          <TextField id="outlined-texto" label="Texto" name="texto" type="text" variant="outlined" 
          multiline style={{width:"100%",paddingBottom:20}} />
          <Button variant="outlined" color="secondary" onClick={handleSubmit}>
            Enviar
          </Button>
        </form>
      </div>
    </Layout>
   
)


const handleSubmit = async ()=>{
  let list: string[] = ["Nome","E-mail","Assunto","Texto"];
  let context : string[] = ["outlined-nome","outlined-email","outlined-assunto","outlined-texto"];

  (document.getElementById("error_contact") as HTMLHtmlElement).innerHTML+= "<div style='flex-grow: 1;flex-basis: 100%' id='texto'></div><br />";
  (document.getElementById("texto") as HTMLHtmlElement).innerHTML= "";
  let cond:boolean = false;

  context.forEach((item, index)=>{ 
    let test : string = (document.getElementById(item) as HTMLInputElement).value;
    if(test.replace(/\s/g,"")===""){
      (document.getElementById("error_contact") as HTMLHtmlElement).style.display="flex";
      (document.getElementById("error_contact") as HTMLHtmlElement).style.flexDirection="row";
      (document.getElementById("error_contact") as HTMLHtmlElement).style.flexWrap="wrap";
      (document.getElementById("texto") as HTMLHtmlElement).innerHTML+= "<div>Preencha o campo "+list[index]+"</div><br />";
      cond=true;
    }
  });

  if(cond==false){
    (document.getElementById("error_contact") as HTMLHtmlElement).style.display="none";
  }
 
  let datas:any = {nome: (document.getElementById("outlined-nome") as HTMLInputElement).value, 
  email: (document.getElementById("outlined-email") as HTMLInputElement).value,
  assunto: (document.getElementById("outlined-assunto") as HTMLInputElement).value,
  texto: (document.getElementById("outlined-texto") as HTMLInputElement).value};

  try {
  let res = await fetch(process.env.url_contact, {
    method: 'post',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(datas)
  });
  console.log(res);
}catch(error){
  alert(error);
}
 
}



export default Contato;

Upvotes: 0

Views: 175

Answers (1)

Aman Bhardwaj
Aman Bhardwaj

Reputation: 1689

If it's just a CORS issue then installing cors and initializing it in your node server should be able to do the trick.

  • Install it with npm or yarn.
yarn add cors
  • Then in your node server:-
const cors = require('cors');
app.use(cors());
  • You can find more about this package here.

Upvotes: 1

Related Questions